import*as e from"../../core/common/common.js";import*as t from"../../core/i18n/i18n.js";import*as s from"../../core/platform/platform.js";import*as o from"../../core/sdk/sdk.js";import*as n from"../../ui/legacy/legacy.js";import*as i from"../../models/text_utils/text_utils.js";import*as r from"../../core/root/root.js";import*as l from"../../third_party/codemirror.next/codemirror.next.js";import*as a from"../../ui/components/text_editor/text_editor.js";import*as c from"../../ui/legacy/components/object_ui/object_ui.js";import*as d from"../../ui/legacy/components/utils/utils.js";import*as h from"../../models/bindings/bindings.js";import*as u from"../../models/logs/logs.js";import*as m from"../../core/host/host.js";import*as p from"../../models/workspace/workspace.js";import*as g from"../../ui/components/code_highlighter/code_highlighter.js";import*as v from"../../ui/components/icon_button/icon_button.js";import*as f from"../../ui/components/issue_counter/issue_counter.js";import*as b from"../../ui/components/request_link_icon/request_link_icon.js";import*as C from"../../ui/legacy/components/data_grid/data_grid.js";import*as w from"../../models/formatter/formatter.js";import*as x from"../../models/source_map_scopes/source_map_scopes.js";import*as S from"../../models/issues_manager/issues_manager.js";const I=new CSSStyleSheet;I.replaceSync(":host{padding:2px 1px 2px 2px;white-space:nowrap;display:flex;flex-direction:column;height:36px;justify-content:center;overflow-y:auto}.title{overflow:hidden;text-overflow:ellipsis;flex-grow:0}.badge{pointer-events:none;margin-right:4px;display:inline-block;height:15px}.subtitle{color:var(--color-text-secondary);margin-right:3px;overflow:hidden;text-overflow:ellipsis;flex-grow:0}:host(.highlighted) .subtitle{color:inherit}\n/*# sourceURL=consoleContextSelector.css */\n");const M={javascriptContextNotSelected:"JavaScript context: Not selected",extension:"Extension",javascriptContextS:"JavaScript context: {PH1}"},E=t.i18n.registerUIStrings("panels/console/ConsoleContextSelector.ts",M),y=t.i18n.getLocalizedString.bind(void 0,E);class T{items;dropDown;toolbarItemInternal;constructor(){this.items=new n.ListModel.ListModel,this.dropDown=new n.SoftDropDown.SoftDropDown(this.items,this),this.dropDown.setRowHeight(36),this.toolbarItemInternal=new n.Toolbar.ToolbarItem(this.dropDown.element),this.toolbarItemInternal.setEnabled(!1),this.toolbarItemInternal.setTitle(y(M.javascriptContextNotSelected)),this.items.addEventListener(n.ListModel.Events.ItemsReplaced,(()=>this.toolbarItemInternal.setEnabled(Boolean(this.items.length)))),this.toolbarItemInternal.element.classList.add("toolbar-has-dropdown"),o.TargetManager.TargetManager.instance().addModelListener(o.RuntimeModel.RuntimeModel,o.RuntimeModel.Events.ExecutionContextCreated,this.onExecutionContextCreated,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.RuntimeModel.RuntimeModel,o.RuntimeModel.Events.ExecutionContextChanged,this.onExecutionContextChanged,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.RuntimeModel.RuntimeModel,o.RuntimeModel.Events.ExecutionContextDestroyed,this.onExecutionContextDestroyed,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.ResourceTreeModel.ResourceTreeModel,o.ResourceTreeModel.Events.FrameNavigated,this.frameNavigated,this,{scoped:!0}),n.Context.Context.instance().addFlavorChangeListener(o.RuntimeModel.ExecutionContext,this.executionContextChangedExternally,this),n.Context.Context.instance().addFlavorChangeListener(o.DebuggerModel.CallFrame,this.callFrameSelectedInUI,this),o.TargetManager.TargetManager.instance().observeModels(o.RuntimeModel.RuntimeModel,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.CallFrameSelected,this.callFrameSelectedInModel,this)}toolbarItem(){return this.toolbarItemInternal}highlightedItemChanged(e,t,s,n){if(o.OverlayModel.OverlayModel.hideDOMNodeHighlight(),t&&t.frameId){const e=o.FrameManager.FrameManager.instance().getFrame(t.frameId);e&&!e.isOutermostFrame()&&e.highlight()}s&&s.classList.remove("highlighted"),n&&n.classList.add("highlighted")}titleFor(e){const t=e.target(),s=e.label();let n=s?t.decorateLabel(s):"";if(e.frameId){const s=t.model(o.ResourceTreeModel.ResourceTreeModel),i=s&&s.frameForId(e.frameId);i&&(n=n||i.displayName())}return n=n||e.origin,n}depthFor(e){let t=e.target(),s=0;if(e.isDefault||s++,e.frameId){let n=o.FrameManager.FrameManager.instance().getFrame(e.frameId);for(;n;)n=n.parentFrame(),n&&(s++,t=n.resourceTreeModel().target())}let n=0,i=t.parentTarget();for(;i&&t.type()!==o.Target.Type.ServiceWorker;)n++,t=i,i=t.parentTarget();return s+=n,s}executionContextCreated(e){this.items.insertWithComparator(e,e.runtimeModel.executionContextComparator()),e===n.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext)&&this.dropDown.selectItem(e)}onExecutionContextCreated(e){const t=e.data;this.executionContextCreated(t)}onExecutionContextChanged(e){const t=e.data;-1!==this.items.indexOf(t)&&(this.executionContextDestroyed(t),this.executionContextCreated(t))}executionContextDestroyed(e){const t=this.items.indexOf(e);-1!==t&&this.items.remove(t)}onExecutionContextDestroyed(e){const t=e.data;this.executionContextDestroyed(t)}executionContextChangedExternally({data:e}){e&&!o.TargetManager.TargetManager.instance().isInScope(e.target())||this.dropDown.selectItem(e)}isTopContext(e){if(!e||!e.isDefault)return!1;const t=e.target().model(o.ResourceTreeModel.ResourceTreeModel),s=e.frameId&&t&&t.frameForId(e.frameId);return!!s&&s.isOutermostFrame()}hasTopContext(){return this.items.some((e=>this.isTopContext(e)))}modelAdded(e){e.executionContexts().forEach(this.executionContextCreated,this)}modelRemoved(e){for(let t=this.items.length-1;t>=0;t--)this.items.at(t).runtimeModel===e&&this.executionContextDestroyed(this.items.at(t))}createElementForItem(e){const t=document.createElement("div"),o=n.Utils.createShadowRootWithCoreStyles(t,{cssFile:[I],delegatesFocus:void 0}),i=o.createChild("div","title");n.UIUtils.createTextChild(i,s.StringUtilities.trimEndWithMaxLength(this.titleFor(e),100));const r=o.createChild("div","subtitle");return n.UIUtils.createTextChild(r,this.subtitleFor(e)),t.style.paddingLeft=8+15*this.depthFor(e)+"px",t}subtitleFor(t){const s=t.target();let n=null;if(t.frameId){const e=s.model(o.ResourceTreeModel.ResourceTreeModel);n=e&&e.frameForId(t.frameId)}if(t.origin.startsWith("chrome-extension://"))return y(M.extension);const i=n&&n.sameTargetParentFrame();if(!n||!i||i.securityOrigin!==t.origin){const s=e.ParsedURL.ParsedURL.fromString(t.origin);if(s)return s.domain()}if(n&&n.securityOrigin){const t=new e.ParsedURL.ParsedURL(n.securityOrigin).domain();if(t)return t}return"IFrame"}isItemSelectable(e){const t=e.debuggerModel.selectedCallFrame(),s=t&&t.script.executionContext();return!s||e===s}itemSelected(e){this.toolbarItemInternal.element.classList.toggle("highlight",!this.isTopContext(e)&&this.hasTopContext());const t=e?y(M.javascriptContextS,{PH1:this.titleFor(e)}):y(M.javascriptContextNotSelected);this.toolbarItemInternal.setTitle(t),n.Context.Context.instance().setFlavor(o.RuntimeModel.ExecutionContext,e)}callFrameSelectedInUI(){const e=n.Context.Context.instance().flavor(o.DebuggerModel.CallFrame),t=e&&e.script.executionContext();t&&n.Context.Context.instance().setFlavor(o.RuntimeModel.ExecutionContext,t)}callFrameSelectedInModel(e){const t=e.data;for(const e of this.items)e.debuggerModel===t&&this.dropDown.refreshItem(e)}frameNavigated(e){const t=e.data,s=t.resourceTreeModel().target().model(o.RuntimeModel.RuntimeModel);if(s)for(const e of s.executionContexts())t.id===e.frameId&&this.dropDown.refreshItem(e)}}var k,L=Object.freeze({__proto__:null,ConsoleContextSelector:T});class F{name;parsedFilters;executionContext;levelsMask;constructor(e,t,s,o){this.name=e,this.parsedFilters=t,this.executionContext=s,this.levelsMask=o||F.defaultLevelsFilterValue()}static allLevelsFilterValue(){const e={},t={Verbose:"verbose",Info:"info",Warning:"warning",Error:"error"};for(const s of Object.values(t))e[s]=!0;return e}static defaultLevelsFilterValue(){const e=F.allLevelsFilterValue();return e.verbose=!1,e}static singleLevelMask(e){const t={};return t[e]=!0,t}clone(){const e=this.parsedFilters.map(i.TextUtils.FilterParser.cloneFilter),t=Object.assign({},this.levelsMask);return new F(this.name,e,this.executionContext,t)}shouldBeVisible(e){const t=e.consoleMessage();return(!this.executionContext||this.executionContext.runtimeModel===t.runtimeModel()&&this.executionContext.id===t.getExecutionContextId())&&(t.type===o.ConsoleModel.FrontendMessageType.Command||t.type===o.ConsoleModel.FrontendMessageType.Result||"endGroup"===t.type||!(t.level&&!this.levelsMask[t.level])&&(this.applyFilter(e)||this.parentGroupHasMatch(e.consoleGroup())))}parentGroupHasMatch(e){return null!==e&&(this.applyFilter(e)||this.parentGroupHasMatch(e.consoleGroup()))}applyFilter(e){const t=e.consoleMessage();for(const n of this.parsedFilters)if(n.key)switch(n.key){case k.Context:if(!s(n,t.context,!1))return!1;break;case k.Source:if(!s(n,t.source?o.ConsoleModel.MessageSourceDisplayName.get(t.source):t.source,!0))return!1;break;case k.Url:if(!s(n,t.url,!1))return!1}else{if(n.regex&&e.matchesFilterRegex(n.regex)===n.negative)return!1;if(n.text&&e.matchesFilterText(n.text)===n.negative)return!1}return!0;function s(e,t,s){if(!e.text)return Boolean(t)===e.negative;if(!t)return!e.text==!e.negative;const o=e.text.toLowerCase(),n=t.toLowerCase();return(!s||n===o!==e.negative)&&!(!s&&n.includes(o)===e.negative)}}}!function(e){e.Context="context",e.Source="source",e.Url="url"}(k||(k={}));var R=Object.freeze({__proto__:null,ConsoleFilter:F,get FilterType(){return k}});const P=["black","red","green","yellow","blue","magenta","cyan","gray"],A=["darkgray","lightred","lightgreen","lightyellow","lightblue","lightmagenta","lightcyan","white"],B=(e,t)=>{const s=[],o=new Map;function n(e){const t=o.get("text-decoration")??"";t.includes(e)||o.set("text-decoration",`${t} ${e}`)}function i(e){const t=o.get("text-decoration")?.replace(` ${e}`,"");t?o.set("text-decoration",t):o.delete("text-decoration")}function r(e){e&&(s.length&&"string"===s[s.length-1].type?s[s.length-1].value+=e:s.push({type:"string",value:e}))}let l=0;const a=/%([%_Oocsdfi])|\x1B\[([\d;]*)m/;for(let c=a.exec(e);null!==c;c=a.exec(e)){let a;r(c.input.substring(0,c.index));const d=c[1];switch(d){case"%":r("%"),a="";break;case"s":if(l<t.length){const{description:e}=t[l++];a=e??""}break;case"c":if(l<t.length){const e="style",o=t[l++].description??"";s.push({type:e,value:o}),a=""}break;case"o":case"O":if(l<t.length){const e="O"===d?"generic":"optimal",o=t[l++];s.push({type:e,value:o}),a=""}break;case"_":l<t.length&&(l++,a="");break;case"d":case"f":case"i":if(l<t.length){const{value:e}=t[l++];a="number"!=typeof e?NaN:e,"f"!==d&&(a=Math.floor(a))}break;case void 0:{const e=(c[2]||"0").split(";").map((e=>e?parseInt(e,10):0));for(;e.length;){const t=e.shift();switch(t){case 0:o.clear();break;case 1:o.set("font-weight","bold");break;case 2:o.set("font-weight","lighter");break;case 3:o.set("font-style","italic");break;case 4:n("underline");break;case 9:n("line-through");break;case 22:o.delete("font-weight");break;case 23:o.delete("font-style");break;case 24:i("underline");break;case 29:i("line-through");break;case 38:case 48:if(2===e.shift()){const s=e.shift()??0,n=e.shift()??0,i=e.shift()??0;o.set(38===t?"color":"background-color",`rgb(${s},${n},${i})`)}break;case 39:case 49:o.delete(39===t?"color":"background-color");break;case 53:n("overline");break;case 55:i("overline");break;default:{const e=P[t-30]??A[t-90];if(void 0!==e)o.set("color",`var(--console-color-${e})`);else{const e=P[t-40]??A[t-100];void 0!==e&&o.set("background-color",`var(--console-color-${e})`)}break}}}const t=[...o.entries()].map((([e,t])=>`${e}:${t.trimStart()}`)).join(";"),r="style";s.push({type:r,value:t}),a="";break}}void 0===a&&(r(c[0]),a=""),e=a+c.input.substring(c.index+c[0].length)}return r(e),{tokens:s,args:t.slice(l)}},H=(e,t)=>{const s=["background","border","color","font","line","margin","padding","text"],o=/url\([\'\"]?([^\)]*)/g;e.clear();const n=document.createElement("span");n.setAttribute("style",t);for(const t of n.style){if(!s.some((e=>t.startsWith(e)||t.startsWith(`-webkit-${e}`))))continue;const i=n.style.getPropertyValue(t);[...i.matchAll(o)].map((e=>e[1])).some((e=>!e.startsWith("data:")))||e.set(t,{value:i,priority:n.style.getPropertyPriority(t)})}};var U=Object.freeze({__proto__:null,format:B,updateStyle:H});const O=new CSSStyleSheet;O.replaceSync(".value.object-value-node:hover{background-color:var(--item-hover-color)}.object-value-function-prefix,\n.object-value-boolean{color:var(--color-syntax-3)}.object-value-function{font-style:italic}.object-value-function.linkified:hover{--override-linkified-hover-background:rgb(0 0 0/10%);background-color:var(--override-linkified-hover-background);cursor:pointer}.-theme-with-dark-background .object-value-function.linkified:hover,\n:host-context(.-theme-with-dark-background) .object-value-function.linkified:hover{--override-linkified-hover-background:rgb(230 230 230/10%)}.object-value-number{color:var(--color-syntax-3)}.object-value-bigint{color:var(--color-syntax-6)}.object-value-string,\n.object-value-regexp,\n.object-value-symbol{white-space:pre;unicode-bidi:-webkit-isolate;color:var(--color-syntax-1)}.object-value-node{position:relative;vertical-align:baseline;color:var(--color-syntax-7);white-space:nowrap}.object-value-null,\n.object-value-undefined{color:var(--color-text-disabled)}.object-value-unavailable{color:var(--color-syntax-2)}.object-value-calculate-value-button:hover{text-decoration:underline}.object-properties-section-custom-section{display:inline-flex;flex-direction:column}.-theme-with-dark-background .object-value-number,\n:host-context(.-theme-with-dark-background) .object-value-number,\n.-theme-with-dark-background .object-value-boolean,\n:host-context(.-theme-with-dark-background) .object-value-boolean{--override-primitive-dark-mode-color:hsl(252deg 100% 75%);color:var(--override-primitive-dark-mode-color)}.object-properties-section .object-description{color:var(--color-text-secondary)}.value .object-properties-preview{white-space:nowrap}.name{color:var(--color-syntax-2);flex-shrink:0}.object-properties-preview .name{color:var(--color-text-secondary)}@media (forced-colors: active){.object-value-calculate-value-button:hover{forced-color-adjust:none;color:Highlight}}\n/*# sourceURL=objectValue.css */\n");const V=new CSSStyleSheet;V.replaceSync(".close-button{position:absolute;top:3px;left:0}.console-pins{max-height:200px;overflow-y:auto;background:var(--color-background-elevation-1);--override-error-background-color:rgb(255 240 240);--override-error-border-color:rgb(225 214 214);--override-error-text-color:rgb(255 0 0)}.console-pins:not(:empty){border-bottom:1px solid var(--color-details-hairline)}.-theme-with-dark-background .console-pins,\n:host-context(.-theme-with-dark-background) .console-pins{--override-error-background-color:rgb(41 0 0);--override-error-border-color:rgb(92 0 0);--override-error-text-color:rgb(255 128 128)}.console-pin{position:relative;user-select:text;flex:none;padding:2px 0 6px 24px}.console-pin:not(:last-child){border-bottom:1px solid var(--color-background-elevation-2)}.console-pin.error-level:not(:focus-within){background-color:var(--override-error-background-color);color:var(--override-error-text-color)}.console-pin:not(:last-child).error-level:not(:focus-within){border-top:1px solid var(--override-error-border-color);border-bottom:1px solid var(--override-error-border-color);margin-top:-1px}.console-pin-name{margin-left:-4px;margin-bottom:1px;height:auto}.console-pin-name,\n.console-pin-preview{width:100%;text-overflow:ellipsis;white-space:nowrap;min-height:13px}.console-pin-preview{overflow:hidden}.console-pin-name:focus-within{background:var(--color-background);box-shadow:var(--legacy-focus-ring-active-shadow) inset}.console-pin:focus-within .console-pin-preview,\n.console-pin-name:not(:focus-within):not(:hover){opacity:60%}\n/*# sourceURL=consolePinPane.css */\n");const N={removeExpression:"Remove expression",removeAllExpressions:"Remove all expressions",removeExpressionS:"Remove expression: {PH1}",removeBlankExpression:"Remove blank expression",liveExpressionEditor:"Live expression editor",expression:"Expression",evaluateAllowingSideEffects:"Evaluate, allowing side effects",notAvailable:"not available"},j=t.i18n.registerUIStrings("panels/console/ConsolePinPane.ts",N),G=t.i18n.getLocalizedString.bind(void 0,j),D=new WeakMap;class W extends n.ThrottledWidget.ThrottledWidget{liveExpressionButton;focusOut;pins;pinsSetting;constructor(t,s){super(!0,250),this.liveExpressionButton=t,this.focusOut=s,this.contentElement.classList.add("console-pins","monospace"),this.contentElement.addEventListener("contextmenu",this.contextMenuEventFired.bind(this),!1),this.pins=new Set,this.pinsSetting=e.Settings.Settings.instance().createLocalSetting("consolePins",[]);for(const e of this.pinsSetting.get())this.addPin(e)}wasShown(){super.wasShown(),this.registerCSSFiles([V,O])}willHide(){for(const e of this.pins)e.setHovered(!1)}savePins(){const e=Array.from(this.pins).map((e=>e.expression()));this.pinsSetting.set(e)}contextMenuEventFired(e){const t=new n.ContextMenu.ContextMenu(e),s=n.UIUtils.deepElementFromEvent(e);if(s){const e=s.enclosingNodeOrSelfWithClass("console-pin");if(e){const s=D.get(e);s&&(t.editSection().appendItem(G(N.removeExpression),this.removePin.bind(this,s)),s.appendToContextMenu(t))}}t.editSection().appendItem(G(N.removeAllExpressions),this.removeAllPins.bind(this)),t.show()}removeAllPins(){for(const e of this.pins)this.removePin(e)}removePin(e){e.element().remove();const t=this.focusedPinAfterDeletion(e);this.pins.delete(e),this.savePins(),t?t.focus():this.liveExpressionButton.focus()}addPin(e,t){const s=new _(e,this,this.focusOut);this.contentElement.appendChild(s.element()),this.pins.add(s),this.savePins(),t&&s.focus(),this.update()}focusedPinAfterDeletion(e){const t=Array.from(this.pins);for(let s=0;s<t.length;s++)if(t[s]===e)return 1===t.length?null:s===t.length-1?t[s-1]:t[s+1];return null}async doUpdate(){if(!this.pins.size||!this.isShowing())return;this.isShowing()&&this.update();const e=Array.from(this.pins,(e=>e.updatePreview()));await Promise.all(e),this.updatedForTest()}updatedForTest(){}}class _{pinPane;focusOut;pinElement;pinPreview;lastResult;lastExecutionContext;editor;committedExpression;hovered;lastNode;deletePinIcon;constructor(t,s,o){this.pinPane=s,this.focusOut=o,this.deletePinIcon=document.createElement("div",{is:"dt-close-button"}),this.deletePinIcon.classList.add("close-button"),this.deletePinIcon.setTabbable(!0),t.length?this.deletePinIcon.setAccessibleName(G(N.removeExpressionS,{PH1:t})):this.deletePinIcon.setAccessibleName(G(N.removeBlankExpression)),self.onInvokeElement(this.deletePinIcon,(e=>{s.removePin(this),e.consume(!0)}));const i=n.Fragment.Fragment.build`
  <div class='console-pin'>
  ${this.deletePinIcon}
  <div class='console-pin-name' $='name'></div>
  <div class='console-pin-preview' $='preview'></div>
  </div>`;this.pinElement=i.element(),this.pinPreview=i.$("preview");const r=i.$("name");n.Tooltip.Tooltip.install(r,t),D.set(this.pinElement,this),this.lastResult=null,this.lastExecutionContext=null,this.committedExpression=t,this.hovered=!1,this.lastNode=null,this.editor=this.createEditor(t,r),this.pinPreview.addEventListener("mouseenter",this.setHovered.bind(this,!0),!1),this.pinPreview.addEventListener("mouseleave",this.setHovered.bind(this,!1),!1),this.pinPreview.addEventListener("click",(t=>{this.lastNode&&(e.Revealer.reveal(this.lastNode),t.consume())}),!1),r.addEventListener("keydown",(e=>{"Escape"===e.key&&e.consume()}))}createEditor(e,t){const s=[l.EditorView.contentAttributes.of({"aria-label":G(N.liveExpressionEditor)}),l.EditorView.lineWrapping,l.javascript.javascriptLanguage,a.Config.showCompletionHint,l.placeholder(G(N.expression)),l.keymap.of([{key:"Escape",run:e=>(e.dispatch({changes:{from:0,to:e.state.doc.length,insert:this.committedExpression}}),this.focusOut(),!0)},{key:"Enter",run:()=>(this.focusOut(),!0)},{key:"Mod-Enter",run:()=>(this.focusOut(),!0)}]),l.EditorView.domEventHandlers({blur:(e,t)=>this.onBlur(t)}),a.Config.baseConfiguration(e),a.Config.closeBrackets,a.Config.autocompletion.instance()];"true"!==r.Runtime.Runtime.queryParam("noJavaScriptCompletion")&&s.push(a.JavaScript.completion());const o=new a.TextEditor.TextEditor(l.EditorState.create({doc:e,extensions:s}));return t.appendChild(o),o}onBlur(e){const t=e.state.doc.toString(),s=t.trim();this.committedExpression=s,this.pinPane.savePins(),this.committedExpression.length?this.deletePinIcon.setAccessibleName(G(N.removeExpressionS,{PH1:this.committedExpression})):this.deletePinIcon.setAccessibleName(G(N.removeBlankExpression)),e.dispatch({selection:{anchor:s.length},changes:s!==t?{from:0,to:t.length,insert:s}:void 0})}setHovered(e){this.hovered!==e&&(this.hovered=e,!e&&this.lastNode&&o.OverlayModel.OverlayModel.hideDOMNodeHighlight())}expression(){return this.committedExpression}element(){return this.pinElement}async focus(){const e=this.editor;e.editor.focus(),e.dispatch({selection:{anchor:e.state.doc.length}})}appendToContextMenu(e){this.lastResult&&!("error"in this.lastResult)&&this.lastResult.object&&(e.appendApplicableItems(this.lastResult.object),this.lastResult=null)}async updatePreview(){if(!this.editor)return;const e=a.Config.contentIncludingHint(this.editor.editor),t=this.pinElement.hasFocus(),s=t&&e!==this.committedExpression,i=s?250:void 0,r=n.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext),{preview:l,result:d}=await c.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(e,s,!0,i,!t,"console",!0,!0);this.lastResult&&this.lastExecutionContext&&this.lastExecutionContext.runtimeModel.releaseEvaluationResult(this.lastResult),this.lastResult=d||null,this.lastExecutionContext=r||null;const h=l.deepTextContent();if(!h||h!==this.pinPreview.deepTextContent()){if(this.pinPreview.removeChildren(),d&&o.RuntimeModel.RuntimeModel.isSideEffectFailure(d)){const e=this.pinPreview.createChild("span","object-value-calculate-value-button");e.textContent="(…)",n.Tooltip.Tooltip.install(e,G(N.evaluateAllowingSideEffects))}else h?this.pinPreview.appendChild(l):t||n.UIUtils.createTextChild(this.pinPreview,G(N.notAvailable));n.Tooltip.Tooltip.install(this.pinPreview,h)}let u=null;d&&!("error"in d)&&"object"===d.object.type&&"node"===d.object.subtype&&(u=d.object),this.hovered&&(u?o.OverlayModel.OverlayModel.highlightObjectAsDOMNode(u):this.lastNode&&o.OverlayModel.OverlayModel.hideDOMNodeHighlight()),this.lastNode=u||null;const m=d&&!("error"in d)&&d.exceptionDetails&&!o.RuntimeModel.RuntimeModel.isSideEffectFailure(d);this.pinElement.classList.toggle("error-level",Boolean(m))}}var z=Object.freeze({__proto__:null,ConsolePinPane:W,ConsolePin:_});const q=new CSSStyleSheet;q.replaceSync(':host{overflow:auto;background-color:var(--color-background-elevation-1)}.tree-outline-disclosure{max-width:100%;padding-left:6px}.count{flex:none;margin:0 8px}[is="ui-icon"]{margin:0 5px}li{height:24px}.tree-element-title{flex-shrink:100;flex-grow:1;overflow:hidden;text-overflow:ellipsis}.tree-outline li:hover:not(.selected) .selection{display:block;background-color:var(--item-hover-color)}[is="ui-icon"].cross-circle{background-color:var(--icon-error)}[is="ui-icon"].warning{background-color:var(--icon-warning)}[is="ui-icon"].info{background-color:var(--icon-info)}@media (forced-colors: active){[is="ui-icon"].icon-mask{background-color:ButtonText}.tree-outline li:hover:not(.selected) .selection{forced-color-adjust:none;background-color:Highlight}.tree-outline li:hover .tree-element-title,\n  .tree-outline li.selected .tree-element-title,\n  .tree-outline li:hover .count,\n  .tree-outline li.selected .count{forced-color-adjust:none;color:HighlightText}.tree-outline li:hover [is="ui-icon"].icon-mask,\n  .tree-outline li.selected [is="ui-icon"].icon-mask,\n  .tree-outline li.selected:focus .spritesheet-mediumicons:not(.icon-mask){background-color:HighlightText!important}}\n/*# sourceURL=consoleSidebar.css */\n');const $={other:"<other>",dUserMessages:"{n, plural, =0 {No user messages} =1 {# user message} other {# user messages}}",dMessages:"{n, plural, =0 {No messages} =1 {# message} other {# messages}}",dErrors:"{n, plural, =0 {No errors} =1 {# error} other {# errors}}",dWarnings:"{n, plural, =0 {No warnings} =1 {# warning} other {# warnings}}",dInfo:"{n, plural, =0 {No info} =1 {# info} other {# info}}",dVerbose:"{n, plural, =0 {No verbose} =1 {# verbose} other {# verbose}}"},K=t.i18n.registerUIStrings("panels/console/ConsoleSidebar.ts",$),J=t.i18n.getLocalizedString.bind(void 0,K);class X extends(e.ObjectWrapper.eventMixin(n.Widget.VBox)){tree;selectedTreeElement;treeElements;constructor(){super(!0),this.setMinimumSize(125,0),this.tree=new n.TreeOutline.TreeOutlineInShadow,this.tree.addEventListener(n.TreeOutline.Events.ElementSelected,this.selectionChanged.bind(this)),this.contentElement.appendChild(this.tree.element),this.selectedTreeElement=null,this.treeElements=[];const t=e.Settings.Settings.instance().createSetting("console.sidebarSelectedFilter",null),s=[{key:k.Source,text:o.ConsoleModel.FrontendMessageSource.ConsoleAPI,negative:!1,regex:void 0}];this.appendGroup("message",[],F.allLevelsFilterValue(),n.Icon.Icon.create("list"),t),this.appendGroup("user message",s,F.allLevelsFilterValue(),n.Icon.Icon.create("profile"),t),this.appendGroup("error",[],F.singleLevelMask("error"),n.Icon.Icon.create("cross-circle"),t),this.appendGroup("warning",[],F.singleLevelMask("warning"),n.Icon.Icon.create("warning"),t),this.appendGroup("info",[],F.singleLevelMask("info"),n.Icon.Icon.create("info"),t),this.appendGroup("verbose",[],F.singleLevelMask("verbose"),n.Icon.Icon.create("bug"),t);const i=t.get();(this.treeElements.find((e=>e.name()===i))||this.treeElements[0]).select()}appendGroup(e,t,s,o,n){const i=new F(e,t,null,s),r=new ee(i,o,n);this.tree.appendChild(r),this.treeElements.push(r)}clear(){for(const e of this.treeElements)e.clear()}onMessageAdded(e){for(const t of this.treeElements)t.onMessageAdded(e)}shouldBeVisible(e){return!(this.selectedTreeElement instanceof Z)||this.selectedTreeElement.filter().shouldBeVisible(e)}selectionChanged(e){this.selectedTreeElement=e.data,this.dispatchEventToListeners("FilterSelected")}wasShown(){super.wasShown(),this.tree.registerCSSFiles([q])}}class Z extends n.TreeOutline.TreeElement{filterInternal;constructor(e,t){super(e),this.filterInternal=t}filter(){return this.filterInternal}}class Q extends Z{countElement;messageCount;constructor(e){super(e.name,e),this.countElement=this.listItemElement.createChild("span","count");const t=[n.Icon.Icon.create("document")];this.setLeadingIcons(t),this.messageCount=0}incrementAndUpdateCounter(){this.messageCount++,this.countElement.textContent=`${this.messageCount}`}}const Y=new Map([["user message",$.dUserMessages],["message",$.dMessages],["error",$.dErrors],["warning",$.dWarnings],["info",$.dInfo],["verbose",$.dVerbose]]);class ee extends Z{selectedFilterSetting;urlTreeElements;messageCount;uiStringForFilterCount;constructor(e,t,s){super(e.name,e),this.uiStringForFilterCount=Y.get(e.name)||"",this.selectedFilterSetting=s,this.urlTreeElements=new Map,this.setLeadingIcons([t]),this.messageCount=0,this.updateCounter()}clear(){this.urlTreeElements.clear(),this.removeChildren(),this.messageCount=0,this.updateCounter()}name(){return this.filterInternal.name}onselect(e){return this.selectedFilterSetting.set(this.filterInternal.name),super.onselect(e)}updateCounter(){this.title=this.updateGroupTitle(this.messageCount),this.setExpandable(Boolean(this.childCount()))}updateGroupTitle(e){return this.uiStringForFilterCount?J(this.uiStringForFilterCount,{n:e}):""}onMessageAdded(e){const t=e.consoleMessage(),s=t.type!==o.ConsoleModel.FrontendMessageType.Command&&t.type!==o.ConsoleModel.FrontendMessageType.Result&&!t.isGroupMessage();if(!this.filterInternal.shouldBeVisible(e)||!s)return;this.childElement(t.url).incrementAndUpdateCounter(),this.messageCount++,this.updateCounter()}childElement(t){const s=t||null;let o=this.urlTreeElements.get(s);if(o)return o;const n=this.filterInternal.clone(),i=s?e.ParsedURL.ParsedURL.fromString(s):null;return n.name=s?i?i.displayName:s:J($.other),n.parsedFilters.push({key:k.Url,text:s,negative:!1,regex:void 0}),o=new Q(n),s&&(o.tooltip=s),this.urlTreeElements.set(s,o),this.appendChild(o),o}}var te=Object.freeze({__proto__:null,ConsoleSidebar:X,URLGroupTreeElement:Q,FilterTreeElement:ee});class se{element;topGapElement;topGapElementActive;contentElementInternal;bottomGapElement;bottomGapElementActive;provider;virtualSelectedIndex;firstActiveIndex;lastActiveIndex;renderedItems;anchorSelection;headSelection;itemCount;cumulativeHeights;muteCopyHandler;observer;observerConfig;stickToBottomInternal;selectionIsBackward;lastSelectedElement;cachedProviderElements;constructor(e){this.element=document.createElement("div"),this.element.style.overflow="auto",this.topGapElement=this.element.createChild("div"),this.topGapElement.style.height="0px",this.topGapElement.style.color="transparent",this.topGapElementActive=!1,this.contentElementInternal=this.element.createChild("div"),this.bottomGapElement=this.element.createChild("div"),this.bottomGapElement.style.height="0px",this.bottomGapElement.style.color="transparent",this.bottomGapElementActive=!1,this.topGapElement.textContent="\ufeff",this.bottomGapElement.textContent="\ufeff",n.ARIAUtils.markAsHidden(this.topGapElement),n.ARIAUtils.markAsHidden(this.bottomGapElement),this.provider=e,this.element.addEventListener("scroll",this.onScroll.bind(this),!1),this.element.addEventListener("copy",this.onCopy.bind(this),!1),this.element.addEventListener("dragstart",this.onDragStart.bind(this),!1),this.contentElementInternal.addEventListener("focusin",this.onFocusIn.bind(this),!1),this.contentElementInternal.addEventListener("focusout",this.onFocusOut.bind(this),!1),this.contentElementInternal.addEventListener("keydown",this.onKeyDown.bind(this),!1),this.virtualSelectedIndex=-1,this.contentElementInternal.tabIndex=-1,this.firstActiveIndex=-1,this.lastActiveIndex=-1,this.renderedItems=[],this.anchorSelection=null,this.headSelection=null,this.itemCount=0,this.cumulativeHeights=new Int32Array(0),this.muteCopyHandler=!1,this.observer=new MutationObserver(this.refresh.bind(this)),this.observerConfig={childList:!0,subtree:!0},this.stickToBottomInternal=!1,this.selectionIsBackward=!1}stickToBottom(){return this.stickToBottomInternal}setStickToBottom(e){this.stickToBottomInternal=e,this.stickToBottomInternal?this.observer.observe(this.contentElementInternal,this.observerConfig):this.observer.disconnect()}hasVirtualSelection(){return-1!==this.virtualSelectedIndex}copyWithStyles(){this.muteCopyHandler=!0,this.element.ownerDocument.execCommand("copy"),this.muteCopyHandler=!1}onCopy(e){if(this.muteCopyHandler)return;const t=this.selectedText();t&&(e.preventDefault(),this.selectionContainsTable()?this.copyWithStyles():e.clipboardData&&e.clipboardData.setData("text/plain",t))}onFocusIn(e){const t=this.renderedItems.findIndex((t=>t.element().isSelfOrAncestor(e.target)));-1!==t&&(this.virtualSelectedIndex=this.firstActiveIndex+t);let s=!1;-1===this.virtualSelectedIndex&&this.isOutsideViewport(e.relatedTarget)&&e.target===this.contentElementInternal&&this.itemCount&&(s=!0,this.virtualSelectedIndex=this.itemCount-1,this.refresh(),this.scrollItemIntoView(this.virtualSelectedIndex)),this.updateFocusedItem(s)}onFocusOut(e){this.isOutsideViewport(e.relatedTarget)&&(this.virtualSelectedIndex=-1),this.updateFocusedItem()}isOutsideViewport(e){return null!==e&&!e.isSelfOrDescendant(this.contentElementInternal)}onDragStart(e){const t=this.selectedText();return!!t&&(e.dataTransfer&&(e.dataTransfer.clearData(),e.dataTransfer.setData("text/plain",t),e.dataTransfer.effectAllowed="copy"),!0)}onKeyDown(e){if(n.UIUtils.isEditing()||!this.itemCount||e.shiftKey)return;let t=!1;switch(e.key){case"ArrowUp":if(!(this.virtualSelectedIndex>0))return;t=!0,this.virtualSelectedIndex--;break;case"ArrowDown":if(!(this.virtualSelectedIndex<this.itemCount-1))return;this.virtualSelectedIndex++;break;case"Home":this.virtualSelectedIndex=0;break;case"End":this.virtualSelectedIndex=this.itemCount-1;break;default:return}e.consume(!0),this.scrollItemIntoView(this.virtualSelectedIndex),this.updateFocusedItem(t)}updateFocusedItem(e){const t=this.renderedElementAt(this.virtualSelectedIndex),o=this.lastSelectedElement!==t,n=this.contentElementInternal===s.DOMUtilities.deepActiveElement(this.element.ownerDocument);this.lastSelectedElement&&o&&this.lastSelectedElement.classList.remove("console-selected"),t&&(e||o||n)&&this.element.hasFocus()&&(t.classList.add("console-selected"),e?(this.setStickToBottom(!1),this.renderedItems[this.virtualSelectedIndex-this.firstActiveIndex].focusLastChildOrSelf()):t.hasFocus()||t.focus({preventScroll:!0})),this.itemCount&&!this.contentElementInternal.hasFocus()?this.contentElementInternal.tabIndex=0:this.contentElementInternal.tabIndex=-1,this.lastSelectedElement=t}contentElement(){return this.contentElementInternal}invalidate(){delete this.cachedProviderElements,this.itemCount=this.provider.itemCount(),this.virtualSelectedIndex>this.itemCount-1&&(this.virtualSelectedIndex=this.itemCount-1),this.rebuildCumulativeHeights(),this.refresh()}providerElement(e){this.cachedProviderElements||(this.cachedProviderElements=new Array(this.itemCount));let t=this.cachedProviderElements[e];return t||(t=this.provider.itemElement(e),this.cachedProviderElements[e]=t),t}rebuildCumulativeHeights(){const e=this.firstActiveIndex,t=this.lastActiveIndex;let s=0;this.cumulativeHeights=new Int32Array(this.itemCount);for(let o=0;o<this.itemCount;++o)e<=o&&o-e<this.renderedItems.length&&o<=t?s+=this.renderedItems[o-e].element().offsetHeight:s+=this.provider.fastHeight(o),this.cumulativeHeights[o]=s}rebuildCumulativeHeightsIfNeeded(){let e=0,t=0;for(let s=0;s<this.renderedItems.length;++s){const o=this.cachedItemHeight(this.firstActiveIndex+s),n=this.renderedItems[s].element().offsetHeight;if(Math.abs(o-n)>1)return void this.rebuildCumulativeHeights();if(t+=n,e+=o,Math.abs(e-t)>1)return void this.rebuildCumulativeHeights()}}cachedItemHeight(e){return 0===e?this.cumulativeHeights[0]:this.cumulativeHeights[e]-this.cumulativeHeights[e-1]}isSelectionBackwards(e){if(!(e&&e.rangeCount&&e.anchorNode&&e.focusNode))return!1;const t=document.createRange();return t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.collapsed}createSelectionModel(e,t,s){return{item:e,node:t,offset:s}}updateSelectionModel(e){const t=e&&e.rangeCount?e.getRangeAt(0):null;if(!t||!e||e.isCollapsed||!this.element.hasSelection())return this.headSelection=null,this.anchorSelection=null,!1;let s=Number.MAX_VALUE,o=-1,n=!1;for(let e=0;e<this.renderedItems.length;++e)if(t.intersectsNode(this.renderedItems[e].element())){const t=e+this.firstActiveIndex;s=Math.min(s,t),o=Math.max(o,t),n=!0}const i=t.intersectsNode(this.topGapElement)&&this.topGapElementActive,r=t.intersectsNode(this.bottomGapElement)&&this.bottomGapElementActive;if(!i&&!r&&!n)return this.headSelection=null,this.anchorSelection=null,!1;this.anchorSelection&&this.headSelection||(this.anchorSelection=this.createSelectionModel(0,this.element,0),this.headSelection=this.createSelectionModel(this.itemCount-1,this.element,this.element.children.length),this.selectionIsBackward=!1);const l=this.isSelectionBackwards(e),a=this.selectionIsBackward?this.headSelection:this.anchorSelection,c=this.selectionIsBackward?this.anchorSelection:this.headSelection;let d=null,h=null;return n&&(d=this.createSelectionModel(s,t.startContainer,t.startOffset),h=this.createSelectionModel(o,t.endContainer,t.endOffset)),i&&r&&n?(d=d&&d.item<a.item?d:a,h=h&&h.item>c.item?h:c):n?i?d=l?this.headSelection:this.anchorSelection:r&&(h=l?this.anchorSelection:this.headSelection):(d=a,h=c),l?(this.anchorSelection=h,this.headSelection=d):(this.anchorSelection=d,this.headSelection=h),this.selectionIsBackward=l,!0}restoreSelection(e){if(!e||!this.anchorSelection||!this.headSelection)return;const t=(e,t)=>{if(this.firstActiveIndex<=e.item&&e.item<=this.lastActiveIndex)return{element:e.node,offset:e.offset};return{element:e.item<this.firstActiveIndex?this.topGapElement:this.bottomGapElement,offset:t?1:0}},{element:s,offset:o}=t(this.anchorSelection,Boolean(this.selectionIsBackward)),{element:n,offset:i}=t(this.headSelection,!this.selectionIsBackward);e.setBaseAndExtent(s,o,n,i)}selectionContainsTable(){if(!this.anchorSelection||!this.headSelection)return!1;const e=this.selectionIsBackward?this.headSelection.item:this.anchorSelection.item,t=this.selectionIsBackward?this.anchorSelection.item:this.headSelection.item;for(let s=e;s<=t;s++){const e=this.providerElement(s);if(e&&"table"===e.consoleMessage().type)return!0}return!1}refresh(){this.observer.disconnect(),this.innerRefresh(),this.stickToBottomInternal&&this.observer.observe(this.contentElementInternal,this.observerConfig)}innerRefresh(){if(!this.visibleHeight())return;if(!this.itemCount){for(let e=0;e<this.renderedItems.length;++e)this.renderedItems[e].willHide();return this.renderedItems=[],this.contentElementInternal.removeChildren(),this.topGapElement.style.height="0px",this.bottomGapElement.style.height="0px",this.firstActiveIndex=-1,this.lastActiveIndex=-1,void this.updateFocusedItem()}const e=this.element.getComponentSelection(),t=this.updateSelectionModel(e),o=this.element.scrollTop,n=this.visibleHeight(),i=2*n;this.rebuildCumulativeHeightsIfNeeded(),this.stickToBottomInternal?(this.firstActiveIndex=Math.max(this.itemCount-Math.ceil(i/this.provider.minimumRowHeight()),0),this.lastActiveIndex=this.itemCount-1):(this.firstActiveIndex=Math.max(s.ArrayUtilities.lowerBound(this.cumulativeHeights,o+1-(i-n)/2,s.ArrayUtilities.DEFAULT_COMPARATOR),0),this.lastActiveIndex=this.firstActiveIndex+Math.ceil(i/this.provider.minimumRowHeight())-1,this.lastActiveIndex=Math.min(this.lastActiveIndex,this.itemCount-1));const r=this.cumulativeHeights[this.firstActiveIndex-1]||0,l=this.cumulativeHeights[this.cumulativeHeights.length-1]-this.cumulativeHeights[this.lastActiveIndex];this.partialViewportUpdate(function(){this.topGapElement.style.height=r+"px",this.bottomGapElement.style.height=l+"px",this.topGapElementActive=Boolean(r),this.bottomGapElementActive=Boolean(l),this.contentElementInternal.style.setProperty("height","10000000px")}.bind(this)),this.contentElementInternal.style.removeProperty("height"),t&&this.restoreSelection(e),this.stickToBottomInternal&&(this.element.scrollTop=1e7)}partialViewportUpdate(e){const t=new Set;for(let e=this.firstActiveIndex;e<=this.lastActiveIndex;++e){const s=this.providerElement(e);console.assert(Boolean(s),"Expected provider element to be defined"),s&&t.add(s)}const s=this.renderedItems.filter((e=>!t.has(e)));for(let e=0;e<s.length;++e)s[e].willHide();e();let o=!1;for(let e=0;e<s.length;++e)o=o||s[e].element().hasFocus(),s[e].element().remove();const n=[];let i=this.contentElementInternal.firstChild;for(const e of t){const t=e.element();if(t!==i){!t.parentElement&&n.push(e),this.contentElementInternal.insertBefore(t,i)}else i=i.nextSibling}for(let e=0;e<n.length;++e)n[e].wasShown();this.renderedItems=Array.from(t),o&&this.contentElementInternal.focus(),this.updateFocusedItem()}selectedText(){if(this.updateSelectionModel(this.element.getComponentSelection()),!this.headSelection||!this.anchorSelection)return null;let e=null,t=null;this.selectionIsBackward?(e=this.headSelection,t=this.anchorSelection):(e=this.anchorSelection,t=this.headSelection);const s=[];for(let o=e.item;o<=t.item;++o){const e=this.providerElement(o);if(console.assert(Boolean(e)),!e)continue;const t=e.element().childTextNodes().map(d.Linkifier.Linkifier.untruncatedNodeText).join("");s.push(t)}const o=this.providerElement(t.item),n=o&&o.element();if(n&&t.node&&t.node.isSelfOrDescendant(n)){const e=this.textOffsetInNode(n,t.node,t.offset);s.length>0&&(s[s.length-1]=s[s.length-1].substring(0,e))}const i=this.providerElement(e.item),r=i&&i.element();if(r&&e.node&&e.node.isSelfOrDescendant(r)){const t=this.textOffsetInNode(r,e.node,e.offset);s[0]=s[0].substring(t)}return s.join("\n")}textOffsetInNode(e,t,s){const o=t.textContent?t.textContent.length:0;t.nodeType!==Node.TEXT_NODE&&(s<t.childNodes.length?(t=t.childNodes.item(s),s=0):s=o);let n=0,i=e;for(;(i=i.traverseNextNode(e))&&i!==t;)i.nodeType!==Node.TEXT_NODE||i.parentNode&&("STYLE"===i.parentNode.nodeName||"SCRIPT"===i.parentNode.nodeName||"#document-fragment"===i.parentNode.nodeName)||(n+=d.Linkifier.Linkifier.untruncatedNodeText(i).length);const r=d.Linkifier.Linkifier.untruncatedNodeText(t).length;return s>0&&r!==o&&(s=r),n+s}onScroll(e){this.refresh()}firstVisibleIndex(){return this.cumulativeHeights.length?(this.rebuildCumulativeHeightsIfNeeded(),s.ArrayUtilities.lowerBound(this.cumulativeHeights,this.element.scrollTop+1,s.ArrayUtilities.DEFAULT_COMPARATOR)):-1}lastVisibleIndex(){if(!this.cumulativeHeights.length)return-1;this.rebuildCumulativeHeightsIfNeeded();const e=this.element.scrollTop+this.element.clientHeight,t=this.itemCount-1;return s.ArrayUtilities.lowerBound(this.cumulativeHeights,e,s.ArrayUtilities.DEFAULT_COMPARATOR,void 0,t)}renderedElementAt(e){return-1===e||e<this.firstActiveIndex||e>this.lastActiveIndex?null:this.renderedItems[e-this.firstActiveIndex].element()}scrollItemIntoView(e,t){const s=this.firstVisibleIndex(),o=this.lastVisibleIndex();e>s&&e<o||e===o&&this.cumulativeHeights[e]<=this.element.scrollTop+this.visibleHeight()||(t?this.forceScrollItemToBeLast(e):e<=s?this.forceScrollItemToBeFirst(e):e>=o&&this.forceScrollItemToBeLast(e))}forceScrollItemToBeFirst(e){console.assert(e>=0&&e<this.itemCount,"Cannot scroll item at invalid index"),this.setStickToBottom(!1),this.rebuildCumulativeHeightsIfNeeded(),this.element.scrollTop=e>0?this.cumulativeHeights[e-1]:0,n.UIUtils.isScrolledToBottom(this.element)&&this.setStickToBottom(!0),this.refresh();const t=this.renderedElementAt(e);t&&t.scrollIntoView(!0)}forceScrollItemToBeLast(e){console.assert(e>=0&&e<this.itemCount,"Cannot scroll item at invalid index"),this.setStickToBottom(!1),this.rebuildCumulativeHeightsIfNeeded(),this.element.scrollTop=this.cumulativeHeights[e]-this.visibleHeight(),n.UIUtils.isScrolledToBottom(this.element)&&this.setStickToBottom(!0),this.refresh();const t=this.renderedElementAt(e);t&&t.scrollIntoView(!1)}visibleHeight(){return this.element.offsetHeight}}var oe=Object.freeze({__proto__:null,ConsoleViewport:se});const ne=new CSSStyleSheet;function ie(t,s){if(!/^[\w.]*Error\b/.test(s))return null;const o=t.debuggerModel(),n=t.target().inspectedURL(),i=s.split("\n"),r=[];for(const t of i){const s=/^\s*at\s/.test(t);if(!s&&r.length&&r[r.length-1].link)return null;if(!s){r.push({line:t});continue}let i=-1,l=-1;const a=/\([^\)\(]+:\d+:\d+\)/g,c=/\([^\)\(]+\)/g;let d,h=null;for(;d=a.exec(t);)h=d;if(!h)for(;d=c.exec(t);)h=d;h&&(i=h.index,l=h.index+h[0].length-1);const u=-1!==i;let m=u?i+1:t.indexOf("at")+3;u||t.indexOf("async ")!==m||(m+=6);const p=u?l:t.length,g=t.substring(m,p),v=e.ParsedURL.ParsedURL.splitLineAndColumn(g);if("<anonymous>"===v.url){r.push({line:t});continue}let f=re(o,v.url);if(!f&&e.ParsedURL.ParsedURL.isRelativeURL(v.url)&&(f=re(o,e.ParsedURL.ParsedURL.completeURL(n,v.url))),!f)return null;r.push({line:t,link:{url:f,prefix:t.substring(0,m),suffix:t.substring(p),enclosedInBraces:u,lineNumber:v.lineNumber,columnNumber:v.columnNumber}})}return r}function re(t,s){if(!s)return null;if(e.ParsedURL.ParsedURL.isValidUrlString(s))return s;if(t.scriptsForSourceURL(s).length)return s;const o=new URL(s,"file://");return t.scriptsForSourceURL(o.href).length?o.href:null}function le(e,t){for(const s of e){const e=t.callFrames.find((e=>ae(s,e)));e&&s.link&&(s.link.scriptId=e.scriptId)}}function ae(e,t){if(!e.link)return!1;const{url:s,lineNumber:o,columnNumber:n}=e.link;return s===t.url&&o===t.lineNumber&&n===t.columnNumber}ne.replaceSync('.console-view{background-color:var(--color-background);overflow:hidden;--override-error-text-color:var(--color-error-text);--override-console-error-background-color:var(--color-error-background);--override-error-border-color:var(--color-error-border);--override-message-border-color:rgb(240 240 240);--override-warning-border-color:hsl(50deg 100% 88%);--override-focused-message-border-color:hsl(214deg 67% 88%);--override-focused-message-background-color:hsl(214deg 48% 95%);--override-console-warning-background-color:hsl(50deg 100% 95%);--override-console-warning-text-color:hsl(39deg 100% 18%)}.-theme-with-dark-background .console-view{--override-message-border-color:rgb(58 58 58);--override-warning-border-color:rgb(102 85 0);--override-focused-message-border-color:hsl(214deg 47% 48%);--override-focused-message-background-color:hsl(214deg 19% 20%);--override-console-warning-background-color:hsl(50deg 100% 10%);--override-console-warning-text-color:hsl(39deg 89% 55%);--override-console-link-color:var(--color-background-inverted)}.console-toolbar-container{display:flex;flex:none}.console-main-toolbar{flex:1 1 auto}.console-toolbar-container > .toolbar{background-color:var(--color-background-elevation-1);border-bottom:var(--legacy-divider-border)}.console-view-fix-select-all{height:0;overflow:hidden}.console-settings-pane{flex:none;background-color:var(--color-background-elevation-1);border-bottom:var(--legacy-divider-border)}.console-settings-pane .toolbar{flex:1 1}#console-messages{flex:1 1;overflow-y:auto;word-wrap:break-word;user-select:text;transform:translateZ(0);overflow-anchor:none;background-color:var(--color-background)}#console-prompt{clear:right;position:relative;margin:0 22px 0 20px}.console-prompt-editor-container{min-height:21px}.console-message,\n.console-user-command{clear:right;position:relative;padding:3px 22px 1px 0;margin-left:24px;min-height:17px;flex:auto;display:flex}.console-message > *{flex:auto}.console-timestamp{color:var(--color-text-secondary);user-select:none;flex:none;margin-right:5px}.message-level-icon,\n.command-result-icon{position:absolute;left:-17px;top:2px;user-select:none}.console-message-repeat-count{margin:2px 0 0 10px;flex:none}.repeated-message{margin-left:4px}.repeated-message .message-level-icon{display:none}.console-message-stack-trace-toggle{display:flex;flex-direction:row;align-items:flex-start}.repeated-message .console-message-stack-trace-toggle,\n.repeated-message > .console-message-text{flex:1}.console-error-level .repeated-message,\n.console-warning-level .repeated-message,\n.console-verbose-level .repeated-message,\n.console-info-level .repeated-message{display:flex}.console-info{color:var(--color-text-secondary);font-style:italic;padding-bottom:2px}.console-group .console-group > .console-group-messages{margin-left:16px}.console-group-title.console-from-api{font-weight:bold}.console-group-title .console-message{margin-left:12px}.expand-group-icon{user-select:none;flex:none;position:relative;left:8px;top:3px;margin-right:2px}.console-group-title .message-level-icon{display:none}.console-message-repeat-count .expand-group-icon{position:static;background-color:var(--color-background);margin-left:-1px}.console-group{position:relative}.console-message-wrapper{display:flex;border-top:1px solid var(--override-message-border-color);border-bottom:1px solid transparent;--console-color-black:#000;--console-color-red:#a00;--console-color-green:#0a0;--console-color-yellow:#a50;--console-color-blue:#00a;--console-color-magenta:#a0a;--console-color-cyan:#0aa;--console-color-gray:#aaa;--console-color-darkgray:#555;--console-color-lightred:#f55;--console-color-lightgreen:#5f5;--console-color-lightyellow:#ff5;--console-color-lightblue:#55f;--console-color-ightmagenta:#f5f;--console-color-lightcyan:#5ff;--console-color-white:#fff}.-theme-with-dark-background .console-message-wrapper{--console-color-red:rgb(237 78 76);--console-color-green:rgb(1 200 1);--console-color-yellow:rgb(210 192 87);--console-color-blue:rgb(39 116 240);--console-color-magenta:rgb(161 66 244);--console-color-cyan:rgb(18 181 203);--console-color-gray:rgb(207 208 208);--console-color-darkgray:rgb(137 137 137);--console-color-lightred:rgb(242 139 130);--console-color-lightgreen:rgb(161 247 181);--console-color-lightyellow:rgb(221 251 85);--console-color-lightblue:rgb(102 157 246);--console-color-lightmagenta:rgb(214 112 214);--console-color-lightcyan:rgb(132 240 255)}.console-message-wrapper:first-of-type{border-top-color:transparent}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level):not(.console-warning-level){border-top-width:0}.console-message-wrapper:last-of-type{border-bottom-color:var(--override-message-border-color)}.console-message-wrapper:focus{border-top-color:var(--override-focused-message-border-color);border-bottom-color:var(--override-focused-message-border-color);background-color:var(--override-focused-message-background-color)}.console-message-wrapper:focus + .console-message-wrapper{border-top-color:transparent}.console-message-wrapper.console-error-level,\n.console-message-wrapper.console-error-level:not(:focus) + .console-message-wrapper:not(.console-warning-level):not(:focus){border-top-color:var(--override-error-border-color)}.console-message-wrapper.console-warning-level,\n.console-message-wrapper.console-warning-level:not(:focus) + .console-message-wrapper:not(.console-error-level):not(:focus){border-top-color:var(--override-warning-border-color)}.console-message-wrapper.console-error-level:last-of-type{border-bottom-color:var(--override-error-border-color)}.console-message-wrapper.console-warning-level:last-of-type{border-bottom-color:var(--override-warning-border-color)}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level):not(.console-warning-level):focus{border-top-width:1px}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level):not(.console-warning-level):focus .console-message{padding-top:2px;min-height:16px}.console-message-wrapper.console-adjacent-user-command-result:not(.console-error-level):not(.console-warning-level):focus .command-result-icon{top:3px}.console-message-wrapper.console-error-level:focus{--override-error-text-color:rgb(200 0 0)}.-theme-with-dark-background .console-message-wrapper.console-error-level:focus{--override-error-text-color:hsl(0deg 100% 75%)}.console-message-wrapper .nesting-level-marker{width:14px;flex:0 0 auto;border-right:1px solid var(--color-details-hairline);position:relative;margin-bottom:-1px;margin-top:-1px}.console-message-wrapper .nesting-level-marker::before{border-bottom:1px solid var(--color-details-hairline);position:absolute;top:0;left:0;margin-left:100%;width:3px;height:100%;box-sizing:border-box}.console-message-wrapper:last-child .nesting-level-marker::before,\n.console-message-wrapper .nesting-level-marker.group-closed::before{content:""}.console-error-level{background-color:var(--override-console-error-background-color)}.console-warning-level{background-color:var(--override-console-warning-background-color)}.console-warning-level .console-message-text{color:var(--override-console-warning-text-color)}.console-view-object-properties-section{padding:0;position:relative;vertical-align:baseline;color:inherit;display:inline-block;overflow-wrap:break-word;max-width:100%}.info-note{background-color:var(--color-primary-variant)}.info-note::before{content:"i"}.console-view-object-properties-section:not(.expanded) .info-note{display:none}.console-error-level .console-message-text,\n.console-error-level .console-view-object-properties-section{color:var(--override-error-text-color)!important}.console-system-type.console-info-level{color:#00f}.-theme-with-dark-background .console-verbose-level:not(.console-warning-level) .console-message-text,\n.-theme-with-dark-background .console-system-type.console-info-level{color:hsl(220deg 100% 65%)!important}#console-messages .link{cursor:pointer;text-decoration:underline}#console-messages .link,\n#console-messages .devtools-link{color:var(--color-text-secondary);word-break:break-all}#console-messages .resource-links{margin-top:-1px;margin-bottom:-2px}#console-messages .link:hover,\n#console-messages .devtools-link:hover{color:var(--color-text-primary)}.console-object-preview{white-space:normal;word-wrap:break-word;font-style:italic}.console-object-preview .name{flex-shrink:0}.console-message-text .object-value-node{display:inline-block}.console-message-text .object-value-string,\n.console-message-text .object-value-regexp,\n.console-message-text .object-value-symbol{white-space:pre-wrap;word-break:break-all}.console-message-formatted-table{clear:both}.console-message .source-code{line-height:1.2}.console-message-anchor{float:right;text-align:right;max-width:100%;margin-left:4px}.console-message-badge{float:right;margin-left:4px}.console-message-nowrap-below,\n.console-message-nowrap-below div,\n.console-message-nowrap-below span{white-space:nowrap!important}.object-state-note{display:inline-block;width:11px;height:11px;color:var(--color-background);text-align:center;border-radius:3px;line-height:13px;margin:0 6px;font-size:9px}.-theme-with-dark-background .object-state-note{background-color:hsl(230deg 100% 80%)}.console-object{white-space:pre-wrap;word-break:break-all}.console-message-stack-trace-wrapper{flex:1 1 auto;display:flex;flex-direction:column;align-items:stretch}.console-message-stack-trace-wrapper > *{flex:none}.console-message-expand-icon{margin-bottom:-4px}.console-searchable-view{max-height:100%}.console-view-pinpane{flex:none;max-height:50%}.message-count{width:0;height:0}.-theme-with-dark-background #console-messages .console-message-text .devtools-link{color:var(--override-console-link-color)}@media (forced-colors: active){.console-message-expand-icon,\n  .console-warning-level [is="ui-icon"].icon-mask.expand-group-icon{forced-color-adjust:none;background-color:ButtonText}.console-message-wrapper:focus,\n  .console-message-wrapper:focus:last-of-type{forced-color-adjust:none;background-color:Highlight;border-top-color:Highlight;border-bottom-color:Highlight}.console-message-wrapper:focus *,\n  .console-message-wrapper:focus:last-of-type *,\n  .console-message-wrapper:focus .devtools-link,\n  .console-message-wrapper:focus:last-of-type .devtools-link{color:HighlightText!important}#console-messages .devtools-link,\n  #console-messages .devtools-link:hover{color:linktext}#console-messages .link:focus-visible,\n  #console-messages .devtools-link:focus-visible{background:Highlight;color:HighlightText}.console-message-wrapper:focus [is="ui-icon"].icon-mask{background-color:HighlightText}.console-message-wrapper.console-error-level:focus,\n  .console-message-wrapper.console-error-level:focus:last-of-type{--override-error-text-color:HighlightText}.console-message-anchor .resource-links{--icon-color:ButtonText}}\n/*# sourceURL=consoleView.css */\n');var ce=Object.freeze({__proto__:null,parseSourcePositionsFromErrorStack:ie,augmentErrorStackWithScriptIds:le});const de={consoleclearWasPreventedDueTo:"`console.clear()` was prevented due to 'Preserve log'",consoleWasCleared:"Console was cleared",clearAllMessagesWithS:"Clear all messages with {PH1}",assertionFailed:"Assertion failed: ",violationS:"`[Violation]` {PH1}",interventionS:"`[Intervention]` {PH1}",deprecationS:"`[Deprecation]` {PH1}",thisValueWillNotBeCollectedUntil:"This value will not be collected until console is cleared.",thisValueWasEvaluatedUponFirst:"This value was evaluated upon first expanding. It may have changed since then.",functionWasResolvedFromBound:"Function was resolved from bound function.",exception:"<exception>",warning:"Warning",error:"Error",logpoint:"Logpoint",cndBreakpoint:"Conditional Breakpoint",repeatS:"{n, plural, =1 {Repeated # time} other {Repeated # times}}",warningS:"{n, plural, =1 {Warning, Repeated # time} other {Warning, Repeated # times}}",errorS:"{n, plural, =1 {Error, Repeated # time} other {Error, Repeated # times}}",url:"<URL>",tookNms:"took <N>ms",someEvent:"<some> event",Mxx:" M<XX>",attribute:"<attribute>",index:"(index)",value:"Value",console:"Console",stackMessageExpanded:"Stack table expanded",stackMessageCollapsed:"Stack table collapsed"},he=t.i18n.registerUIStrings("panels/console/ConsoleViewMessage.ts",de),ue=t.i18n.getLocalizedString.bind(void 0,he),me=new WeakMap,pe=e=>me.get(e),ge=e=>t=>t instanceof o.RemoteObject.RemoteObject?t:e?"object"==typeof t?e.createRemoteObject(t):e.createRemoteObjectFromPrimitiveValue(t):o.RemoteObject.RemoteObject.fromLocalObject(t);class ve{message;linkifier;repeatCountInternal;closeGroupDecorationCount;consoleGroupInternal;selectableChildren;messageResized;elementInternal;previewFormatter;searchRegexInternal;messageIcon;traceExpanded;expandTrace;anchorElement;contentElementInternal;nestingLevelMarkers;searchHighlightNodes;searchHighlightNodeChanges;isVisibleInternal;cachedHeight;messagePrefix;timestampElement;inSimilarGroup;similarGroupMarker;lastInSimilarGroup;groupKeyInternal;repeatCountElement;requestResolver;issueResolver;#e=!1;#t=Promise.resolve();constructor(e,t,s,o,n){this.message=e,this.linkifier=t,this.requestResolver=s,this.issueResolver=o,this.repeatCountInternal=1,this.closeGroupDecorationCount=0,this.selectableChildren=[],this.messageResized=n,this.elementInternal=null,this.previewFormatter=new c.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,this.searchRegexInternal=null,this.messageIcon=null,this.traceExpanded=!1,this.expandTrace=null,this.anchorElement=null,this.contentElementInternal=null,this.nestingLevelMarkers=null,this.searchHighlightNodes=[],this.searchHighlightNodeChanges=[],this.isVisibleInternal=!1,this.cachedHeight=0,this.messagePrefix="",this.timestampElement=null,this.inSimilarGroup=!1,this.similarGroupMarker=null,this.lastInSimilarGroup=!1,this.groupKeyInternal="",this.repeatCountElement=null,this.consoleGroupInternal=null}element(){return this.toMessageElement()}wasShown(){this.isVisibleInternal=!0}onResize(){}willHide(){this.isVisibleInternal=!1,this.cachedHeight=this.element().offsetHeight}isVisible(){return this.isVisibleInternal}fastHeight(){return this.cachedHeight?this.cachedHeight:this.approximateFastHeight()}approximateFastHeight(){return 19}consoleMessage(){return this.message}formatErrorStackPromiseForTest(){return this.#t}buildMessage(){let t,s=this.message.messageText;if(this.message.source===o.ConsoleModel.FrontendMessageSource.ConsoleAPI)switch(this.message.type){case"trace":t=this.format(this.message.parameters||["console.trace"]);break;case"clear":t=document.createElement("span"),t.classList.add("console-info"),e.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()?t.textContent=ue(de.consoleclearWasPreventedDueTo):t.textContent=ue(de.consoleWasCleared),n.Tooltip.Tooltip.install(t,ue(de.clearAllMessagesWithS,{PH1:String(n.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction("console.clear"))}));break;case"dir":{const e=["%O",this.message.parameters?this.message.parameters[0]:void 0];t=this.format(e);break}case"profile":case"profileEnd":t=this.format([s]);break;default:{if("assert"===this.message.type&&(this.messagePrefix=ue(de.assertionFailed)),this.message.parameters&&1===this.message.parameters.length){const e=this.message.parameters[0];"string"!=typeof e&&"string"===e.type&&(t=this.tryFormatAsError(e.value))}const e=this.message.parameters||[s];t=t||this.format(e)}}else if("network"===this.message.source)t=this.formatAsNetworkRequest()||this.format([s]);else{const e=this.message.parameters&&s===this.message.parameters[0];"violation"===this.message.source?s=ue(de.violationS,{PH1:s}):"intervention"===this.message.source?s=ue(de.interventionS,{PH1:s}):"deprecation"===this.message.source&&(s=ue(de.deprecationS,{PH1:s}));const o=this.message.parameters||[s];e&&(o[0]=s),t=this.format(o)}t.classList.add("console-message-text");const i=document.createElement("span");return i.classList.add("source-code"),this.anchorElement=this.buildMessageAnchor(),this.anchorElement&&i.appendChild(this.anchorElement),i.appendChild(t),i}formatAsNetworkRequest(){const e=u.NetworkLog.NetworkLog.requestForConsoleMessage(this.message);if(!e)return null;const t=document.createElement("span");if("error"===this.message.level){n.UIUtils.createTextChild(t,e.requestMethod+" ");const s=d.Linkifier.Linkifier.linkifyRevealable(e,e.url(),e.url());s.tabIndex=-1,this.selectableChildren.push({element:s,forceSelect:()=>s.focus()}),t.appendChild(s),e.failed&&n.UIUtils.createTextChildren(t," ",e.localizedFailDescription||""),0!==e.statusCode&&n.UIUtils.createTextChildren(t," ",String(e.statusCode)),e.statusText&&n.UIUtils.createTextChildren(t," (",e.statusText,")")}else{const s=this.message.messageText,o=this.linkifyWithCustomLinkifier(s,((t,s,o,n)=>{const i=s===e.url()?d.Linkifier.Linkifier.linkifyRevealable(e,s,e.url()):d.Linkifier.Linkifier.linkifyURL(s,{text:t,lineNumber:o,columnNumber:n});return i.tabIndex=-1,this.selectableChildren.push({element:i,forceSelect:()=>i.focus()}),i}));t.appendChild(o)}return t}createAffectedResourceLinks(){const e=[],t=this.message.getAffectedResources()?.requestId;if(t){const s=new b.RequestLinkIcon.RequestLinkIcon;s.classList.add("resource-links"),s.data={affectedRequest:{requestId:t},requestResolver:this.requestResolver,displayURL:!1},e.push(s)}const s=this.message.getAffectedResources()?.issueId;if(s){const t=new f.IssueLinkIcon.IssueLinkIcon;t.classList.add("resource-links"),t.data={issueId:s,issueResolver:this.issueResolver},e.push(t)}return e}#s(){if(u.NetworkLog.NetworkLog.requestForConsoleMessage(this.message)?.resourceType().isStyleSheet())return m.UserMetrics.Action.StyleSheetInitiatorLinkClicked}buildMessageAnchor(){const e=this.message.runtimeModel();if(!e)return null;const t=(({stackFrameWithBreakpoint:t,scriptId:o,stackTrace:n,url:i,line:r,column:l})=>{const a=this.#s();return t?this.linkifier.maybeLinkifyConsoleCallFrame(e.target(),t,{inlineFrameIndex:0,revealBreakpoint:!0,userMetric:a}):o?this.linkifier.linkifyScriptLocation(e.target(),o,i||s.DevToolsPath.EmptyUrlString,r,{columnNumber:l,inlineFrameIndex:0,userMetric:a}):n&&n.callFrames.length?this.linkifier.linkifyStackTraceTopFrame(e.target(),n):i&&"undefined"!==i?this.linkifier.linkifyScriptLocation(e.target(),null,i,r,{columnNumber:l,inlineFrameIndex:0,userMetric:a}):null})(this.message);if(t){t.tabIndex=-1,this.selectableChildren.push({element:t,forceSelect:()=>t.focus()});const e=document.createElement("span");e.classList.add("console-message-anchor"),e.appendChild(t);for(const t of this.createAffectedResourceLinks())n.UIUtils.createTextChild(e," "),e.append(t);return n.UIUtils.createTextChild(e," "),e}return null}buildMessageWithStackTrace(t){const s=document.createElement("div");s.classList.add("console-message-stack-trace-toggle");const o=s.createChild("div","console-message-stack-trace-wrapper"),i=this.buildMessage(),r=n.Icon.Icon.create("triangle-right","console-message-expand-icon"),l=o.createChild("div");n.ARIAUtils.setExpanded(l,!1),l.appendChild(r),l.tabIndex=-1,l.appendChild(i);const a=o.createChild("div"),c=d.JSPresentationUtils.buildStackTracePreviewContents(t.target(),this.linkifier,{stackTrace:this.message.stackTrace,tabStops:void 0});a.appendChild(c.element);for(const e of c.links)this.selectableChildren.push({element:e,forceSelect:()=>e.focus()});a.classList.add("hidden"),n.ARIAUtils.setLabel(o,`${i.textContent} ${ue(de.stackMessageCollapsed)}`),n.ARIAUtils.markAsGroup(a),this.expandTrace=e=>{r.setIconType(e?"triangle-down":"triangle-right"),a.classList.toggle("hidden",!e);const t=ue(e?de.stackMessageExpanded:de.stackMessageCollapsed);n.ARIAUtils.setLabel(o,`${i.textContent} ${t}`),n.ARIAUtils.alert(t),n.ARIAUtils.setExpanded(l,e),this.traceExpanded=e};return l.addEventListener("click",(e=>{n.UIUtils.isEditing()||o.hasSelection()||(this.expandTrace&&this.expandTrace(a.classList.contains("hidden")),e.consume())}),!1),"trace"===this.message.type&&e.Settings.Settings.instance().moduleSetting("consoleTraceExpand").get()&&this.expandTrace(!0),s._expandStackTraceForTest=this.expandTrace.bind(this,!0),s}format(e){const t=document.createElement("span");if(this.messagePrefix&&(t.createChild("span").textContent=this.messagePrefix),!e.length)return t;let s=e.map(ge(this.message.runtimeModel()));const i="string"===o.RemoteObject.RemoteObject.type(s[0])&&(this.message.type!==o.ConsoleModel.FrontendMessageType.Result||"error"===this.message.level);i&&(s=this.formatWithSubstitutionString(s[0].description,s.slice(1),t),s.length&&n.UIUtils.createTextChild(t," "));for(let e=0;e<s.length;++e)i&&"string"===s[e].type?t.appendChild(this.linkifyStringAsFragment(s[e].description||"")):t.appendChild(this.formatParameter(s[e],!1,!0)),e<s.length-1&&n.UIUtils.createTextChild(t," ");return t}formatParameter(e,t,s){if(e.customPreview())return new c.CustomPreviewComponent.CustomPreviewComponent(e).element;const o=t?"object":e.subtype||e.type;let n;switch(o){case"error":n=this.formatParameterAsError(e);break;case"function":n=this.formatParameterAsFunction(e,s);break;case"array":case"arraybuffer":case"blob":case"dataview":case"generator":case"iterator":case"map":case"object":case"promise":case"proxy":case"set":case"typedarray":case"wasmvalue":case"weakmap":case"weakset":case"webassemblymemory":n=this.formatParameterAsObject(e,s);break;case"node":n=e.isNode()?this.formatParameterAsNode(e):this.formatParameterAsObject(e,!1);break;case"trustedtype":n=this.formatParameterAsObject(e,!1);break;case"string":n=this.formatParameterAsString(e);break;case"boolean":case"date":case"null":case"number":case"regexp":case"symbol":case"undefined":case"bigint":n=this.formatParameterAsValue(e);break;default:n=this.formatParameterAsValue(e),console.error(`Tried to format remote object of unknown type ${o}.`)}return n.classList.add(`object-value-${o}`),n.classList.add("source-code"),n}formatParameterAsValue(e){const t=document.createElement("span"),s=e.description||"";if(s.length>Te()){const e=new c.ObjectPropertiesSection.ExpandableTextPropertyValue(document.createElement("span"),s,ke());t.appendChild(e.element)}else n.UIUtils.createTextChild(t,s);return t.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),t}formatParameterAsTrustedType(e){const t=document.createElement("span"),s=document.createElement("span");return s.appendChild(this.formatParameterAsString(e)),s.classList.add("object-value-string"),n.UIUtils.createTextChild(t,`${e.className} `),t.appendChild(s),t}formatParameterAsObject(e,t){const s=document.createElement("span");if(s.classList.add("console-object"),t&&e.preview)s.classList.add("console-object-preview"),this.previewFormatter.appendObjectPreview(s,e.preview,!1),c.ObjectPropertiesSection.ObjectPropertiesSection.appendMemoryIcon(s,e);else if("function"===e.type){const t=s.createChild("span");c.ObjectPropertiesSection.ObjectPropertiesSection.formatObjectAsFunction(e,t,!1),s.classList.add("object-value-function")}else"trustedtype"===e.subtype?s.appendChild(this.formatParameterAsTrustedType(e)):n.UIUtils.createTextChild(s,e.description||"");if(!e.hasChildren||e.customPreview())return s;const i=s.createChild("span","object-state-note info-note");this.message.type===o.ConsoleModel.FrontendMessageType.QueryObjectResult?n.Tooltip.Tooltip.install(i,ue(de.thisValueWillNotBeCollectedUntil)):n.Tooltip.Tooltip.install(i,ue(de.thisValueWasEvaluatedUponFirst));const r=new c.ObjectPropertiesSection.ObjectPropertiesSection(e,s,this.linkifier);return r.element.classList.add("console-view-object-properties-section"),r.enableContextMenu(),r.setShowSelectionOnKeyboardFocus(!0,!0),this.selectableChildren.push(r),r.addEventListener(n.TreeOutline.Events.ElementAttached,this.messageResized),r.addEventListener(n.TreeOutline.Events.ElementExpanded,this.messageResized),r.addEventListener(n.TreeOutline.Events.ElementCollapsed,this.messageResized),r.element}formatParameterAsFunction(e,t){const s=document.createElement("span");return o.RemoteObject.RemoteFunction.objectAsFunction(e).targetFunction().then(function(o){const i=document.createElement("span"),r=c.ObjectPropertiesSection.ObjectPropertiesSection.formatObjectAsFunction(o,i,!0,t);if(s.appendChild(i),o!==e){const e=s.createChild("span","object-state-note info-note");n.Tooltip.Tooltip.install(e,ue(de.functionWasResolvedFromBound))}s.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),r.then((()=>this.formattedParameterAsFunctionForTest()))}.bind(this)),s}formattedParameterAsFunctionForTest(){}contextMenuEventFired(e,t){const s=new n.ContextMenu.ContextMenu(t);s.appendApplicableItems(e),s.show()}renderPropertyPreviewOrAccessor(e,t,s){return"accessor"===t.type?this.formatAsAccessorProperty(e,s.map((e=>e.name.toString())),!1):this.previewFormatter.renderPropertyPreview(t.type,"subtype"in t?t.subtype:void 0,null,t.value)}formatParameterAsNode(e){const t=document.createElement("span"),s=e.runtimeModel().target().model(o.DOMModel.DOMModel);return s?(s.pushObjectAsNodeToFrontend(e).then((async s=>{if(!s)return void t.appendChild(this.formatParameterAsObject(e,!1));const o=await n.UIUtils.Renderer.render(s);o?(o.tree&&(this.selectableChildren.push(o.tree),o.tree.addEventListener(n.TreeOutline.Events.ElementAttached,this.messageResized),o.tree.addEventListener(n.TreeOutline.Events.ElementExpanded,this.messageResized),o.tree.addEventListener(n.TreeOutline.Events.ElementCollapsed,this.messageResized)),t.appendChild(o.node)):t.appendChild(this.formatParameterAsObject(e,!1)),this.formattedParameterAsNodeForTest()})),t):t}formattedParameterAsNodeForTest(){}formatParameterAsString(e){const t=e.description??"",o=s.StringUtilities.formatAsJSLiteral(t),n=document.createElement("span");return n.addEventListener("contextmenu",this.contextMenuEventFired.bind(this,e),!1),n.appendChild(this.linkifyStringAsFragment(o)),n}formatParameterAsError(e){const t=document.createElement("span"),s=e.description||"";return this.#t=this.retrieveExceptionDetails(e).then((e=>{const o=this.tryFormatAsError(s,e);t.appendChild(o??this.linkifyStringAsFragment(s))})),t}async retrieveExceptionDetails(e){const t=this.message.runtimeModel();if(t&&e.objectId)return t.getExceptionDetails(e.objectId)}formatAsArrayEntry(e){return this.previewFormatter.renderPropertyPreview(e.type,e.subtype,e.className,e.description)}formatAsAccessorProperty(e,t,o){const i=c.ObjectPropertiesSection.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(e,t,function(e){const t=e.wasThrown,r=e.object;if(!r)return;if(i.removeChildren(),t){const e=i.createChild("span");e.textContent=ue(de.exception),n.Tooltip.Tooltip.install(e,r.description)}else if(o)i.appendChild(this.formatAsArrayEntry(r));else{const e=100,t=r.type,o=r.subtype;let n="";"function"!==t&&r.description&&(n="string"===t||"regexp"===o||"trustedtype"===o?s.StringUtilities.trimMiddle(r.description,e):s.StringUtilities.trimEndWithMaxLength(r.description,e)),i.appendChild(this.previewFormatter.renderPropertyPreview(t,o,r.className,n))}}.bind(this));return i}formatWithSubstitutionString(e,t,s){const o=new Map,{tokens:n,args:i}=B(e,t);for(const e of n)switch(e.type){case"generic":s.append(this.formatParameter(e.value,!0,!1));break;case"optimal":s.append(this.formatParameter(e.value,!1,!0));break;case"string":if(0===o.size)s.append(this.linkifyStringAsFragment(e.value));else{const t=e.value.split("\n");for(let e=0;e<t.length;e++){e>0&&s.append(document.createElement("br"));const n=document.createElement("span");n.style.setProperty("contain","paint"),n.style.setProperty("display","inline-block"),n.style.setProperty("max-width","100%"),n.appendChild(this.linkifyStringAsFragment(t[e]));for(const[e,{value:t,priority:s}]of o)n.style.setProperty(e,t,s);s.append(n)}}break;case"style":H(o,e.value)}return i}matchesFilterRegex(e){e.lastIndex=0;const t=this.contentElement(),s=this.anchorElement?this.anchorElement.deepTextContent():"";return Boolean(s)&&e.test(s.trim())||e.test(t.deepTextContent().slice(s.length))}matchesFilterText(e){return this.contentElement().deepTextContent().toLowerCase().includes(e.toLowerCase())}updateTimestamp(){this.contentElementInternal&&(e.Settings.Settings.instance().moduleSetting("consoleTimestampsEnabled").get()?(this.timestampElement||(this.timestampElement=document.createElement("span"),this.timestampElement.classList.add("console-timestamp")),this.timestampElement.textContent=n.UIUtils.formatTimestamp(this.message.timestamp,!1)+" ",n.Tooltip.Tooltip.install(this.timestampElement,n.UIUtils.formatTimestamp(this.message.timestamp,!0)),this.contentElementInternal.insertBefore(this.timestampElement,this.contentElementInternal.firstChild)):this.timestampElement&&(this.timestampElement.remove(),this.timestampElement=null))}nestingLevel(){let e=0;for(let t=this.consoleGroup();null!==t;t=t.consoleGroup())e++;return e}setConsoleGroup(e){console.assert(null===this.consoleGroupInternal),this.consoleGroupInternal=e}clearConsoleGroup(){this.consoleGroupInternal=null}consoleGroup(){return this.consoleGroupInternal}setInSimilarGroup(e,t){this.inSimilarGroup=e,this.lastInSimilarGroup=e&&Boolean(t),this.similarGroupMarker&&!e?(this.similarGroupMarker.remove(),this.similarGroupMarker=null):this.elementInternal&&!this.similarGroupMarker&&e&&(this.similarGroupMarker=document.createElement("div"),this.similarGroupMarker.classList.add("nesting-level-marker"),this.elementInternal.insertBefore(this.similarGroupMarker,this.elementInternal.firstChild),this.similarGroupMarker.classList.toggle("group-closed",this.lastInSimilarGroup))}isLastInSimilarGroup(){return Boolean(this.inSimilarGroup)&&Boolean(this.lastInSimilarGroup)}resetCloseGroupDecorationCount(){this.closeGroupDecorationCount&&(this.closeGroupDecorationCount=0,this.updateCloseGroupDecorations())}incrementCloseGroupDecorationCount(){++this.closeGroupDecorationCount,this.updateCloseGroupDecorations()}updateCloseGroupDecorations(){if(this.nestingLevelMarkers)for(let e=0,t=this.nestingLevelMarkers.length;e<t;++e){this.nestingLevelMarkers[e].classList.toggle("group-closed",t-e<=this.closeGroupDecorationCount)}}focusedChildIndex(){return this.selectableChildren.length?this.selectableChildren.findIndex((e=>e.element.hasFocus())):-1}onKeyDown(e){!n.UIUtils.isEditing()&&this.elementInternal&&this.elementInternal.hasFocus()&&!this.elementInternal.hasSelection()&&this.maybeHandleOnKeyDown(e)&&e.consume(!0)}maybeHandleOnKeyDown(e){const t=this.focusedChildIndex(),s=-1===t;if(this.expandTrace&&s&&("ArrowLeft"===e.key&&this.traceExpanded||"ArrowRight"===e.key&&!this.traceExpanded))return this.expandTrace(!this.traceExpanded),!0;if(!this.selectableChildren.length)return!1;if("ArrowLeft"===e.key)return this.elementInternal&&this.elementInternal.focus(),!0;if("ArrowRight"===e.key&&s&&this.selectNearestVisibleChild(0))return!0;if("ArrowUp"===e.key){const e=this.nearestVisibleChild(0);if(this.selectableChildren[t]===e&&e)return this.elementInternal&&this.elementInternal.focus(),!0;if(this.selectNearestVisibleChild(t-1,!0))return!0}if("ArrowDown"===e.key){if(s&&this.selectNearestVisibleChild(0))return!0;if(!s&&this.selectNearestVisibleChild(t+1))return!0}return!1}selectNearestVisibleChild(e,t){const s=this.nearestVisibleChild(e,t);return!!s&&(s.forceSelect(),!0)}nearestVisibleChild(e,t){const s=this.selectableChildren.length;if(e<0||e>=s)return null;const o=t?-1:1;let n=e;for(;!this.selectableChildren[n].element.offsetParent;)if(n+=o,n<0||n>=s)return null;return this.selectableChildren[n]}focusLastChildOrSelf(){this.elementInternal&&!this.selectNearestVisibleChild(this.selectableChildren.length-1,!0)&&this.elementInternal.focus()}setContentElement(e){console.assert(!this.contentElementInternal,"Cannot set content element twice"),this.contentElementInternal=e}getContentElement(){return this.contentElementInternal}contentElement(){if(this.contentElementInternal)return this.contentElementInternal;const e=document.createElement("div");e.classList.add("console-message"),this.messageIcon&&e.appendChild(this.messageIcon),this.contentElementInternal=e;const t=this.message.runtimeModel();let s;const o=Boolean(this.message.stackTrace)&&("network"===this.message.source||"violation"===this.message.source||"error"===this.message.level||"warning"===this.message.level||"trace"===this.message.type);return s=t&&o?this.buildMessageWithStackTrace(t):this.buildMessage(),e.appendChild(s),this.updateTimestamp(),this.contentElementInternal}toMessageElement(){return this.elementInternal||(this.elementInternal=document.createElement("div"),this.elementInternal.tabIndex=-1,this.elementInternal.addEventListener("keydown",this.onKeyDown.bind(this)),this.updateMessageElement(),this.elementInternal.classList.toggle("console-adjacent-user-command-result",this.#e)),this.elementInternal}updateMessageElement(){if(this.elementInternal){this.elementInternal.className="console-message-wrapper",this.elementInternal.removeChildren(),this.message.isGroupStartMessage()&&this.elementInternal.classList.add("console-group-title"),this.message.source===o.ConsoleModel.FrontendMessageSource.ConsoleAPI&&this.elementInternal.classList.add("console-from-api"),this.inSimilarGroup&&(this.similarGroupMarker=this.elementInternal.createChild("div","nesting-level-marker"),this.similarGroupMarker.classList.toggle("group-closed",this.lastInSimilarGroup)),this.nestingLevelMarkers=[];for(let e=0;e<this.nestingLevel();++e)this.nestingLevelMarkers.push(this.elementInternal.createChild("div","nesting-level-marker"));switch(this.updateCloseGroupDecorations(),me.set(this.elementInternal,this),this.message.level){case"verbose":this.elementInternal.classList.add("console-verbose-level");break;case"info":this.elementInternal.classList.add("console-info-level"),this.message.type===o.ConsoleModel.FrontendMessageType.System&&this.elementInternal.classList.add("console-system-type");break;case"warning":this.elementInternal.classList.add("console-warning-level");break;case"error":this.elementInternal.classList.add("console-error-level")}this.updateMessageIcon(),this.shouldRenderAsWarning()&&this.elementInternal.classList.add("console-warning-level"),this.elementInternal.appendChild(this.contentElement()),this.repeatCountInternal>1&&this.showRepeatCountElement()}}shouldRenderAsWarning(){return!("verbose"!==this.message.level&&"info"!==this.message.level||"violation"!==this.message.source&&"deprecation"!==this.message.source&&"intervention"!==this.message.source&&"recommendation"!==this.message.source)}updateMessageIcon(){this.messageIcon&&(this.messageIcon.remove(),this.messageIcon=null);let e="",t="",s="";"warning"===this.message.level?(e="var(--icon-warning)",t="warning-filled",s=ue(de.warning)):"error"===this.message.level?(e="var(--icon-error)",t="cross-circle-filled",s=ue(de.error)):this.message.originatesFromLogpoint?(t="console-logpoint",s=ue(de.logpoint)):this.message.originatesFromConditionalBreakpoint&&(t="console-conditional-breakpoint",s=ue(de.cndBreakpoint)),t&&(this.messageIcon=new v.Icon.Icon,this.messageIcon.data={iconName:t,color:e,width:"14px",height:"14px"},this.messageIcon.classList.add("message-level-icon"),this.contentElementInternal&&this.contentElementInternal.insertBefore(this.messageIcon,this.contentElementInternal.firstChild),n.ARIAUtils.setLabel(this.messageIcon,s))}setAdjacentUserCommandResult(e){this.#e=e,this.elementInternal?.classList.toggle("console-adjacent-user-command-result",this.#e)}repeatCount(){return this.repeatCountInternal||1}resetIncrementRepeatCount(){this.repeatCountInternal=1,this.repeatCountElement&&(this.repeatCountElement.remove(),this.contentElementInternal&&this.contentElementInternal.classList.remove("repeated-message"),this.repeatCountElement=null)}incrementRepeatCount(){this.repeatCountInternal++,this.showRepeatCountElement()}setRepeatCount(e){this.repeatCountInternal=e,this.showRepeatCountElement()}showRepeatCountElement(){if(!this.elementInternal)return;if(!this.repeatCountElement){switch(this.repeatCountElement=document.createElement("span",{is:"dt-small-bubble"}),this.repeatCountElement.classList.add("console-message-repeat-count"),this.message.level){case"warning":this.repeatCountElement.type="warning";break;case"error":this.repeatCountElement.type="error";break;case"verbose":this.repeatCountElement.type="verbose";break;default:this.repeatCountElement.type="info"}this.shouldRenderAsWarning()&&(this.repeatCountElement.type="warning"),this.elementInternal.insertBefore(this.repeatCountElement,this.contentElementInternal),this.contentElement().classList.add("repeated-message")}let e;this.repeatCountElement.textContent=`${this.repeatCountInternal}`,e="warning"===this.message.level?ue(de.warningS,{n:this.repeatCountInternal}):"error"===this.message.level?ue(de.errorS,{n:this.repeatCountInternal}):ue(de.repeatS,{n:this.repeatCountInternal}),n.ARIAUtils.setLabel(this.repeatCountElement,e)}get text(){return this.message.messageText}toExportString(){const e=[],t=this.contentElement().childTextNodes().map(d.Linkifier.Linkifier.untruncatedNodeText).join("");for(let s=0;s<this.repeatCount();++s)e.push(t);return e.join("\n")}setSearchRegex(e){if(this.searchHighlightNodeChanges&&this.searchHighlightNodeChanges.length&&n.UIUtils.revertDomChanges(this.searchHighlightNodeChanges),this.searchRegexInternal=e,this.searchHighlightNodes=[],this.searchHighlightNodeChanges=[],!this.searchRegexInternal)return;const t=this.contentElement().deepTextContent();let s;this.searchRegexInternal.lastIndex=0;const o=[];for(;(s=this.searchRegexInternal.exec(t))&&s[0];)o.push(new i.TextRange.SourceRange(s.index,s[0].length));o.length&&(this.searchHighlightNodes=n.UIUtils.highlightSearchResults(this.contentElement(),o,this.searchHighlightNodeChanges))}searchRegex(){return this.searchRegexInternal}searchCount(){return this.searchHighlightNodes.length}searchHighlightNode(e){return this.searchHighlightNodes[e]}async getInlineFrames(e,t,s,n){const i=h.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance();if(i.pluginManager){const r=p.Workspace.WorkspaceImpl.instance().projects().map((e=>e.uiSourceCodeForURL(t))).flat().filter((e=>Boolean(e))).map((e=>i.scriptsForUISourceCode(e))).flat();if(r.length){const t=new o.DebuggerModel.Location(e,r[0].scriptId,s||0,n),l=await i.pluginManager.getFunctionInfo(r[0],t);return l&&"frames"in l?l:{frames:[]}}}return{frames:[]}}async expandInlineStackFrames(e,t,s,o,n,i,r,l){const{frames:a}=await this.getInlineFrames(e,o,n,i);if(!a.length)return!1;for(let c=0;c<a.length;++c){const{name:d}=a[c],h=document.createElement("span");h.appendChild(this.linkifyStringAsFragment(`${t} ${d} (`));const u=this.linkifier.linkifyScriptLocation(e.target(),null,o,n,{columnNumber:i,inlineFrameIndex:c});u.tabIndex=-1,this.selectableChildren.push({element:u,forceSelect:()=>u.focus()}),h.appendChild(u),h.appendChild(this.linkifyStringAsFragment(s)),r.insertBefore(h,l)}return!0}createScriptLocationLinkForSyntaxError(e,t){const{scriptId:s,lineNumber:o,columnNumber:n}=t;if(!s)return;const i=t.url||e.scriptForId(s)?.sourceURL;if(!i)return;const r=this.linkifier.linkifyScriptLocation(e.target(),t.scriptId||null,i,o,{columnNumber:n,inlineFrameIndex:0,showColumnNumber:!0});return r.tabIndex=-1,r}tryFormatAsError(e,t){const s=this.message.runtimeModel();if(!s)return null;const o=ie(s,e);if(!o?.length)return null;t?.stackTrace&&le(o,t.stackTrace);const n=s.debuggerModel(),i=document.createElement("span");for(let e=0;e<o.length;++e){const s=e<o.length-1?"\n":"",{line:r,link:l}=o[e];if(!l&&t&&r.startsWith("SyntaxError")){i.appendChild(this.linkifyStringAsFragment(r));const e=this.createScriptLocationLinkForSyntaxError(n,t);e&&(i.append(" (at "),i.appendChild(e),i.append(")")),i.append(s);continue}if(!l){i.appendChild(this.linkifyStringAsFragment(`${r}${s}`));continue}const a=document.createElement("span"),c=`${l.suffix}${s}`;a.appendChild(this.linkifyStringAsFragment(l.prefix));const d=this.linkifier.linkifyScriptLocation(n.target(),l.scriptId||null,l.url,l.lineNumber,{columnNumber:l.columnNumber,inlineFrameIndex:0,showColumnNumber:!0});if(d.tabIndex=-1,this.selectableChildren.push({element:d,forceSelect:()=>d.focus()}),a.appendChild(d),a.appendChild(this.linkifyStringAsFragment(c)),i.appendChild(a),!l.enclosedInBraces)continue;const h=l.prefix.substring(0,l.prefix.lastIndexOf(" ",l.prefix.length-3)),u=this.selectableChildren.length-1;this.expandInlineStackFrames(n,h,c,l.url,l.lineNumber,l.columnNumber,i,a).then((e=>{e&&(i.removeChild(a),this.selectableChildren.splice(u,1))}))}return i}linkifyWithCustomLinkifier(t,o){if(t.length>Te()){const e=new c.ObjectPropertiesSection.ExpandableTextPropertyValue(document.createElement("span"),t,ke()),s=document.createDocumentFragment();return s.appendChild(e.element),s}const n=document.createDocumentFragment(),i=ve.tokenizeMessageText(t);let r=!1;for(const t of i)if(t.text)switch(r&&(t.text=`blob:${t.text}`,r=!r),"'blob:"===t.text&&t===i[0]&&(r=!0,t.text="'"),t.type){case"url":{const i=t.text.startsWith("www.")?"http://"+t.text:t.text,r=e.ParsedURL.ParsedURL.splitLineAndColumn(i),l=e.ParsedURL.ParsedURL.removeWasmFunctionInfoFromURL(r.url);let a;a=r?o(t.text,l,r.lineNumber,r.columnNumber):o(t.text,s.DevToolsPath.EmptyUrlString),n.appendChild(a);break}default:n.appendChild(document.createTextNode(t.text))}return n}linkifyStringAsFragment(e){return this.linkifyWithCustomLinkifier(e,((e,t,s,o)=>{const n={text:e,lineNumber:s,columnNumber:o},i=d.Linkifier.Linkifier.linkifyURL(t,n);return i.tabIndex=-1,this.selectableChildren.push({element:i,forceSelect:()=>i.focus()}),i}))}static tokenizeMessageText(e){const{tokenizerRegexes:t,tokenizerTypes:s}=Ce();if(e.length>Te())return[{text:e,type:void 0}];return i.TextUtils.Utils.splitStringByRegexes(e,t).map((e=>({text:e.value,type:s[e.regexIndex]})))}groupKey(){return this.groupKeyInternal||(this.groupKeyInternal=this.message.groupCategoryKey()+":"+this.groupTitle()),this.groupKeyInternal}groupTitle(){return ve.tokenizeMessageText(this.message.messageText).reduce(((e,t)=>{let s=t.text;return"url"===t.type?s=ue(de.url):"time"===t.type?s=ue(de.tookNms):"event"===t.type?s=ue(de.someEvent):"milestone"===t.type?s=ue(de.Mxx):"autofill"===t.type&&(s=ue(de.attribute)),e+s}),"").replace(/[%]o/g,"")}}let fe=null,be=null;function Ce(){if(!fe||!be){const e="\\u0000-\\u0020\\u007f-\\u009f",t=new RegExp("(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|data:|www\\.)[^\\s"+e+'"]{2,}[^\\s'+e+"\"')}\\],:;.!?]","u"),s=/(?:\/[\w\.-]*)+\:[\d]+/,o=/took [\d]+ms/,n=/'\w+' event/,i=/\sM[6-7]\d/,r=/\(suggested: \"[\w-]+\"\)/,l=new Map;return l.set(t,"url"),l.set(s,"url"),l.set(o,"time"),l.set(n,"event"),l.set(i,"milestone"),l.set(r,"autofill"),fe=Array.from(l.keys()),be=Array.from(l.values()),{tokenizerRegexes:fe,tokenizerTypes:be}}return{tokenizerRegexes:fe,tokenizerTypes:be}}class we extends ve{collapsedInternal;expandGroupIcon;onToggle;groupEndMessageInternal;constructor(e,t,s,o,n,i){console.assert(e.isGroupStartMessage()),super(e,t,s,o,i),this.collapsedInternal="startGroupCollapsed"===e.type,this.expandGroupIcon=null,this.onToggle=n,this.groupEndMessageInternal=null}setCollapsed(e){this.collapsedInternal=e,this.expandGroupIcon&&this.expandGroupIcon.setIconType(this.collapsedInternal?"triangle-right":"triangle-down"),this.onToggle.call(null)}collapsed(){return this.collapsedInternal}maybeHandleOnKeyDown(e){return-1===this.focusedChildIndex()&&("ArrowLeft"===e.key&&!this.collapsedInternal||"ArrowRight"===e.key&&this.collapsedInternal)?(this.setCollapsed(!this.collapsedInternal),!0):super.maybeHandleOnKeyDown(e)}toMessageElement(){let e=this.elementInternal||null;if(!e){e=super.toMessageElement();const t=this.collapsedInternal?"triangle-right":"triangle-down";this.expandGroupIcon=n.Icon.Icon.create(t,"expand-group-icon"),this.contentElement().tabIndex=-1,this.repeatCountElement?this.repeatCountElement.insertBefore(this.expandGroupIcon,this.repeatCountElement.firstChild):e.insertBefore(this.expandGroupIcon,this.contentElementInternal),e.addEventListener("click",(()=>this.setCollapsed(!this.collapsedInternal)))}return e}showRepeatCountElement(){super.showRepeatCountElement(),this.repeatCountElement&&this.expandGroupIcon&&this.repeatCountElement.insertBefore(this.expandGroupIcon,this.repeatCountElement.firstChild)}messagesHidden(){if(this.collapsed())return!0;const e=this.consoleGroup();return Boolean(e&&e.messagesHidden())}setGroupEnd(e){if("endGroup"!==e.consoleMessage().type)throw new Error("Invalid console message as group end");if(null!==this.groupEndMessageInternal)throw new Error("Console group already has an end");this.groupEndMessageInternal=e}groupEnd(){return this.groupEndMessageInternal}}class xe extends ve{formattedCommand;constructor(e,t,s,o,n){super(e,t,s,o,n),this.formattedCommand=null}contentElement(){const e=this.getContentElement();if(e)return e;const t=document.createElement("div");this.setContentElement(t),t.classList.add("console-user-command");const o=new v.Icon.Icon;return o.data={iconName:"chevron-right",color:"var(--icon-default)",width:"16px",height:"16px"},o.classList.add("command-result-icon"),t.appendChild(o),me.set(t,this),this.formattedCommand=document.createElement("span"),this.formattedCommand.classList.add("source-code"),this.formattedCommand.textContent=s.StringUtilities.replaceControlCharacters(this.text),t.appendChild(this.formattedCommand),this.formattedCommand.textContent.length<Me?g.CodeHighlighter.highlightNode(this.formattedCommand,"text/javascript").then(this.updateSearch.bind(this)):this.updateSearch(),this.updateTimestamp(),t}updateSearch(){this.setSearchRegex(this.searchRegex())}}class Se extends ve{contentElement(){const e=super.contentElement();if(!e.classList.contains("console-user-command-result")&&(e.classList.add("console-user-command-result"),"info"===this.consoleMessage().level)){const t=new v.Icon.Icon;t.data={iconName:"chevron-left-dot",color:"var(--icon-default)",width:"16px",height:"16px"},t.classList.add("command-result-icon"),e.insertBefore(t,e.firstChild)}return e}}class Ie extends ve{dataGrid;constructor(e,t,s,o,n){super(e,t,s,o,n),console.assert("table"===e.type),this.dataGrid=null}wasShown(){this.dataGrid&&this.dataGrid.updateWidths(),super.wasShown()}onResize(){this.isVisible()&&this.dataGrid&&this.dataGrid.onResize()}contentElement(){const e=this.getContentElement();if(e)return e;const t=document.createElement("div");return t.classList.add("console-message"),this.messageIcon&&t.appendChild(this.messageIcon),this.setContentElement(t),t.appendChild(this.buildTableMessage()),this.updateTimestamp(),t}buildTableMessage(){const e=document.createElement("span");e.classList.add("source-code"),this.anchorElement=this.buildMessageAnchor(),this.anchorElement&&e.appendChild(this.anchorElement);const t=this.message.parameters&&this.message.parameters.length?this.message.parameters[0]:null;if(!t)return this.buildMessage();const s=ge(this.message.runtimeModel())(t);if(!s||!s.preview)return this.buildMessage();const o=Symbol("rawValueColumn"),n=[],i=s.preview,r=[];for(let e=0;e<i.properties.length;++e){const t=i.properties[e];let l;if(t.valuePreview&&t.valuePreview.properties.length)l=t.valuePreview.properties;else{if(!t.value&&""!==t.value)continue;l=[{name:o,type:t.type,value:t.value}]}const a=new Map,c=20;for(let e=0;e<l.length;++e){const o=l[e];let i=-1!==n.indexOf(o.name);if(!i){if(n.length===c)continue;i=!0,n.push(o.name)}if(i){const e=this.renderPropertyPreviewOrAccessor(s,o,[t,o]);e.classList.add("console-message-nowrap-below"),a.set(o.name,e)}}r.push({rowName:t.name,rowValue:a})}const l=[];for(const{rowName:e,rowValue:t}of r){l.push(e);for(let e=0;e<n.length;++e)l.push(t.get(n[e]))}n.unshift(ue(de.index));const a=n.map((e=>e===o?ue(de.value):e.toString()));if(l.length&&(this.dataGrid=C.SortableDataGrid.SortableDataGrid.create(a,l,ue(de.console)),this.dataGrid)){this.dataGrid.setStriped(!0),this.dataGrid.setFocusable(!1);const t=document.createElement("span");t.classList.add("console-message-text");const o=t.createChild("div","console-message-formatted-table"),n=o.createChild("span");o.appendChild(this.formatParameter(s,!0,!1));const i=n.attachShadow({mode:"open"}),r=this.dataGrid.asWidget();r.markAsRoot(),r.show(i),r.registerCSSFiles([ne,O]),e.appendChild(t),this.dataGrid.renderInline()}return e}approximateFastHeight(){const e=this.message.parameters&&this.message.parameters[0];return e&&"string"!=typeof e&&e.preview?19*e.preview.properties.length:19}}const Me=1e4;let Ee=1e4,ye=5e3;const Te=()=>Ee,ke=()=>ye;var Le=Object.freeze({__proto__:null,getMessageForElement:pe,ConsoleViewMessage:ve,ConsoleGroupViewMessage:we,ConsoleCommand:xe,ConsoleCommandResult:Se,ConsoleTableMessageView:Ie,MaxLengthForLinks:40,getMaxTokenizableStringLength:Te,setMaxTokenizableStringLength:e=>{Ee=e},getLongStringVisibleLength:ke,setLongStringVisibleLength:e=>{ye=e}});const Fe={issuesWithColon:"{n, plural, =0 {No Issues} =1 {# Issue:} other {# Issues:}}",issueToolbarTooltipGeneral:"Some problems no longer generate console messages, but are surfaced in the issues tab.",issueToolbarClickToView:"Click to view {issueEnumeration}",issueToolbarClickToGoToTheIssuesTab:"Click to go to the issues tab",findStringInLogs:"Find string in logs",consoleSettings:"Console settings",groupSimilarMessagesInConsole:"Group similar messages in console",showCorsErrorsInConsole:"Show `CORS` errors in console",showConsoleSidebar:"Show console sidebar",hideConsoleSidebar:"Hide console sidebar",consoleSidebarShown:"Console sidebar shown",consoleSidebarHidden:"Console sidebar hidden",doNotClearLogOnPageReload:"Do not clear log on page reload / navigation",preserveLog:"Preserve log",hideNetwork:"Hide network",onlyShowMessagesFromTheCurrentContext:"Only show messages from the current context (`top`, `iframe`, `worker`, extension)",selectedContextOnly:"Selected context only",logXMLHttpRequests:"Log XMLHttpRequests",eagerlyEvaluateTextInThePrompt:"Eagerly evaluate text in the prompt",autocompleteFromHistory:"Autocomplete from history",treatEvaluationAsUserActivation:"Treat evaluation as user activation",sHidden:"{n, plural, =1 {# hidden} other {# hidden}}",consoleCleared:"Console cleared",hideMessagesFromS:"Hide messages from {PH1}",saveAs:"Save as...",copyVisibleStyledSelection:"Copy visible styled selection",replayXhr:"Replay XHR",writingFile:"Writing file…",searching:"Searching…",filter:"Filter",egEventdCdnUrlacom:"e.g. `/eventd/ -cdn url:a.com`",verbose:"Verbose",info:"Info",warnings:"Warnings",errors:"Errors",logLevels:"Log levels",overriddenByFilterSidebar:"Overridden by filter sidebar",customLevels:"Custom levels",sOnly:"{PH1} only",allLevels:"All levels",defaultLevels:"Default levels",hideAll:"Hide all",logLevelS:"Log level: {PH1}",default:"Default",filteredMessagesInConsole:"{PH1} messages in console",consolePasteBlocked:"Pasting code is blocked on this page. Pasting code into devtools can allow attackers to take over your account."},Re=t.i18n.registerUIStrings("panels/console/ConsoleView.ts",Fe),Pe=t.i18n.getLocalizedString.bind(void 0,Re);let Ae,Be;class He extends n.Widget.VBox{searchableViewInternal;sidebar;isSidebarOpen;filter;consoleToolbarContainer;splitWidget;contentsElement;visibleViewMessages;hiddenByFilterCount;shouldBeHiddenCache;lastShownHiddenByFilterCount;currentMatchRangeIndex;searchRegex;groupableMessages;groupableMessageTitle;shortcuts;regexMatchRanges;consoleContextSelector;filterStatusText;showSettingsPaneSetting;showSettingsPaneButton;progressToolbarItem;groupSimilarSetting;showCorsErrorsSetting;timestampsSetting;consoleHistoryAutocompleteSetting;pinPane;viewport;messagesElement;messagesCountElement;viewportThrottler;pendingBatchResize;onMessageResizedBound;promptElement;linkifier;consoleMessages;consoleGroupStarts;prompt;immediatelyFilterMessagesForTest;maybeDirtyWhileMuted;scheduledRefreshPromiseForTest;needsFullUpdate;buildHiddenCacheTimeout;searchShouldJumpBackwards;searchProgressIndicator;innerSearchTimeoutId;muteViewportUpdates;waitForScrollTimeout;issueCounter;pendingSidebarMessages=[];userHasOpenedSidebarAtLeastOnce=!1;issueToolbarThrottle;requestResolver=new u.RequestResolver.RequestResolver;issueResolver=new S.IssueResolver.IssueResolver;constructor(t){super(),this.setMinimumSize(0,35),this.searchableViewInternal=new n.SearchableView.SearchableView(this,null),this.searchableViewInternal.element.classList.add("console-searchable-view"),this.searchableViewInternal.setPlaceholder(Pe(Fe.findStringInLogs)),this.searchableViewInternal.setMinimalSearchQuerySize(0),this.sidebar=new X,this.sidebar.addEventListener("FilterSelected",this.onFilterChanged.bind(this)),this.isSidebarOpen=!1,this.filter=new Ue(this.onFilterChanged.bind(this)),this.consoleToolbarContainer=this.element.createChild("div","console-toolbar-container"),this.splitWidget=new n.SplitWidget.SplitWidget(!0,!1,"console.sidebar.width",100),this.splitWidget.setMainWidget(this.searchableViewInternal),this.splitWidget.setSidebarWidget(this.sidebar),this.splitWidget.show(this.element),this.splitWidget.hideSidebar(),this.splitWidget.enableShowModeSaving(),this.isSidebarOpen=this.splitWidget.showMode()===n.SplitWidget.ShowMode.Both,this.filter.setLevelMenuOverridden(this.isSidebarOpen),this.splitWidget.addEventListener(n.SplitWidget.Events.ShowModeChanged,(e=>{this.isSidebarOpen=e.data===n.SplitWidget.ShowMode.Both,this.isSidebarOpen&&(this.userHasOpenedSidebarAtLeastOnce||(m.userMetrics.actionTaken(m.UserMetrics.Action.ConsoleSidebarOpened),this.userHasOpenedSidebarAtLeastOnce=!0),this.pendingSidebarMessages.forEach((e=>{this.sidebar.onMessageAdded(e)})),this.pendingSidebarMessages=[]),this.filter.setLevelMenuOverridden(this.isSidebarOpen),this.onFilterChanged()})),this.contentsElement=this.searchableViewInternal.element,this.element.classList.add("console-view"),this.visibleViewMessages=[],this.hiddenByFilterCount=0,this.shouldBeHiddenCache=new Set,this.groupableMessages=new Map,this.groupableMessageTitle=new Map,this.shortcuts=new Map,this.regexMatchRanges=[],this.consoleContextSelector=new T,this.filterStatusText=new n.Toolbar.ToolbarText,this.filterStatusText.element.classList.add("dimmed"),this.showSettingsPaneSetting=e.Settings.Settings.instance().createSetting("consoleShowSettingsToolbar",!1),this.showSettingsPaneButton=new n.Toolbar.ToolbarSettingToggle(this.showSettingsPaneSetting,"gear",Pe(Fe.consoleSettings),"gear-filled"),this.progressToolbarItem=new n.Toolbar.ToolbarItem(document.createElement("div")),this.groupSimilarSetting=e.Settings.Settings.instance().moduleSetting("consoleGroupSimilar"),this.groupSimilarSetting.addChangeListener((()=>this.updateMessageList())),this.showCorsErrorsSetting=e.Settings.Settings.instance().moduleSetting("consoleShowsCorsErrors"),this.showCorsErrorsSetting.addChangeListener((()=>this.updateMessageList()));const s=new n.Toolbar.Toolbar("console-main-toolbar",this.consoleToolbarContainer);s.makeWrappable(!0);const i=new n.Toolbar.Toolbar("",this.consoleToolbarContainer);s.appendToolbarItem(this.splitWidget.createShowHideSidebarButton(Pe(Fe.showConsoleSidebar),Pe(Fe.hideConsoleSidebar),Pe(Fe.consoleSidebarShown),Pe(Fe.consoleSidebarHidden))),s.appendToolbarItem(n.Toolbar.Toolbar.createActionButton(n.ActionRegistry.ActionRegistry.instance().action("console.clear"))),s.appendSeparator(),s.appendToolbarItem(this.consoleContextSelector.toolbarItem()),s.appendSeparator();const r=n.Toolbar.Toolbar.createActionButton(n.ActionRegistry.ActionRegistry.instance().action("console.create-pin"));s.appendToolbarItem(r),s.appendSeparator(),s.appendToolbarItem(this.filter.textFilterUI),s.appendToolbarItem(this.filter.levelMenuButton),s.appendToolbarItem(this.progressToolbarItem),s.appendSeparator(),this.issueCounter=new f.IssueCounter.IssueCounter,this.issueCounter.id="console-issues-counter";const l=new n.Toolbar.ToolbarItem(this.issueCounter);this.issueCounter.data={clickHandler:()=>{m.userMetrics.issuesPanelOpenedFrom(m.UserMetrics.IssueOpener.StatusBarIssuesCounter),n.ViewManager.ViewManager.instance().showView("issues-pane")},issuesManager:S.IssuesManager.IssuesManager.instance(),accessibleName:Pe(Fe.issueToolbarTooltipGeneral),displayMode:"OmitEmpty"},s.appendToolbarItem(l),i.appendSeparator(),i.appendToolbarItem(this.filterStatusText),i.appendToolbarItem(this.showSettingsPaneButton);const a=e.Settings.Settings.instance().moduleSetting("monitoringXHREnabled");this.timestampsSetting=e.Settings.Settings.instance().moduleSetting("consoleTimestampsEnabled"),this.consoleHistoryAutocompleteSetting=e.Settings.Settings.instance().moduleSetting("consoleHistoryAutocomplete");const c=new n.Widget.HBox;c.show(this.contentsElement),c.element.classList.add("console-settings-pane"),n.ARIAUtils.setLabel(c.element,Pe(Fe.consoleSettings)),n.ARIAUtils.markAsGroup(c.element);const h=new n.Toolbar.Toolbar("",c.element);h.makeVertical(),He.appendSettingsCheckboxToToolbar(h,this.filter.hideNetworkMessagesSetting,this.filter.hideNetworkMessagesSetting.title(),Pe(Fe.hideNetwork)),He.appendSettingsCheckboxToToolbar(h,"preserveConsoleLog",Pe(Fe.doNotClearLogOnPageReload),Pe(Fe.preserveLog)),He.appendSettingsCheckboxToToolbar(h,this.filter.filterByExecutionContextSetting,Pe(Fe.onlyShowMessagesFromTheCurrentContext),Pe(Fe.selectedContextOnly)),He.appendSettingsCheckboxToToolbar(h,this.groupSimilarSetting,Pe(Fe.groupSimilarMessagesInConsole)),He.appendSettingsCheckboxToToolbar(h,this.showCorsErrorsSetting,Pe(Fe.showCorsErrorsInConsole));const u=new n.Toolbar.Toolbar("",c.element);u.makeVertical(),He.appendSettingsCheckboxToToolbar(u,a,Pe(Fe.logXMLHttpRequests)),He.appendSettingsCheckboxToToolbar(u,"consoleEagerEval",Pe(Fe.eagerlyEvaluateTextInThePrompt)),He.appendSettingsCheckboxToToolbar(u,this.consoleHistoryAutocompleteSetting,Pe(Fe.autocompleteFromHistory)),He.appendSettingsCheckboxToToolbar(u,"consoleUserActivationEval",Pe(Fe.treatEvaluationAsUserActivation)),this.showSettingsPaneSetting.get()||c.element.classList.add("hidden"),this.showSettingsPaneSetting.addChangeListener((()=>c.element.classList.toggle("hidden",!this.showSettingsPaneSetting.get()))),this.pinPane=new W(r,(()=>this.prompt.focus())),this.pinPane.element.classList.add("console-view-pinpane"),this.pinPane.show(this.contentsElement),this.viewport=new se(this),this.viewport.setStickToBottom(!0),this.viewport.contentElement().classList.add("console-group","console-group-messages"),this.contentsElement.appendChild(this.viewport.element),this.messagesElement=this.viewport.element,this.messagesElement.id="console-messages",this.messagesElement.classList.add("monospace"),this.messagesElement.addEventListener("click",this.messagesClicked.bind(this),!1),["paste","clipboard-paste","drop"].forEach((e=>{this.messagesElement.addEventListener(e,this.messagesPasted.bind(this),!0)})),this.messagesCountElement=this.consoleToolbarContainer.createChild("div","message-count"),n.ARIAUtils.markAsPoliteLiveRegion(this.messagesCountElement,!1),this.viewportThrottler=new e.Throttler.Throttler(t),this.pendingBatchResize=!1,this.onMessageResizedBound=e=>{this.onMessageResized(e)},this.promptElement=this.messagesElement.createChild("div","source-code"),this.promptElement.id="console-prompt";const p=this.messagesElement.createChild("div","console-view-fix-select-all");p.textContent=".",n.ARIAUtils.markAsHidden(p),this.registerShortcuts(),this.messagesElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!1);const g=new e.Throttler.Throttler(100);this.linkifier=new d.Linkifier.Linkifier(40,void 0,(()=>g.schedule((async()=>this.onFilterChanged())))),this.consoleMessages=[],this.consoleGroupStarts=[],this.prompt=new Ye,this.prompt.show(this.promptElement),this.prompt.element.addEventListener("keydown",this.promptKeyDown.bind(this),!0),this.prompt.addEventListener("TextChanged",this.promptTextChanged,this),this.messagesElement.addEventListener("keydown",this.messagesKeyDown.bind(this),!1),this.prompt.element.addEventListener("focusin",(()=>{this.isScrolledToBottom()&&this.viewport.setStickToBottom(!0)})),this.consoleHistoryAutocompleteSetting.addChangeListener(this.consoleHistoryAutocompleteChanged,this),this.consoleHistoryAutocompleteChanged(),this.updateFilterStatus(),this.timestampsSetting.addChangeListener(this.consoleTimestampsSettingChanged,this),this.registerWithMessageSink(),n.Context.Context.instance().addFlavorChangeListener(o.RuntimeModel.ExecutionContext,this.executionContextChanged,this),this.messagesElement.addEventListener("mousedown",(e=>this.updateStickToBottomOnPointerDown(2===e.button)),!1),this.messagesElement.addEventListener("mouseup",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("mouseleave",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("wheel",this.updateStickToBottomOnWheel.bind(this),!1),this.messagesElement.addEventListener("touchstart",this.updateStickToBottomOnPointerDown.bind(this,!1),!1),this.messagesElement.addEventListener("touchend",this.updateStickToBottomOnPointerUp.bind(this),!1),this.messagesElement.addEventListener("touchcancel",this.updateStickToBottomOnPointerUp.bind(this),!1),o.TargetManager.TargetManager.instance().addModelListener(o.ConsoleModel.ConsoleModel,o.ConsoleModel.Events.ConsoleCleared,this.consoleCleared,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.ConsoleModel.ConsoleModel,o.ConsoleModel.Events.MessageAdded,this.onConsoleMessageAdded,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.ConsoleModel.ConsoleModel,o.ConsoleModel.Events.MessageUpdated,this.onConsoleMessageUpdated,this,{scoped:!0}),o.TargetManager.TargetManager.instance().addModelListener(o.ConsoleModel.ConsoleModel,o.ConsoleModel.Events.CommandEvaluated,this.commandEvaluated,this,{scoped:!0}),o.TargetManager.TargetManager.instance().observeModels(o.ConsoleModel.ConsoleModel,this,{scoped:!0});const v=S.IssuesManager.IssuesManager.instance();this.issueToolbarThrottle=new e.Throttler.Throttler(100),v.addEventListener("IssuesCountUpdated",(()=>this.issueToolbarThrottle.schedule((async()=>this.updateIssuesToolbarItem()))),this)}static appendSettingsCheckboxToToolbar(t,s,o,i){let r;r="string"==typeof s?e.Settings.Settings.instance().moduleSetting(s):s;const l=new n.Toolbar.ToolbarSettingCheckbox(r,o,i);return t.appendToolbarItem(l),l}static instance(e){return Ae&&!e?.forceNew||(Ae=new He(e?.viewportThrottlerTimeout??50)),Ae}static clearConsole(){o.ConsoleModel.ConsoleModel.requestClearMessages()}modelAdded(e){e.messages().forEach(this.addConsoleMessage,this)}modelRemoved(t){e.Settings.Settings.instance().moduleSetting("preserveConsoleLog").get()||t.target().outermostTarget()!==t.target()||this.consoleCleared()}onFilterChanged(){if(this.filter.currentFilter.levelsMask=this.isSidebarOpen?F.allLevelsFilterValue():this.filter.messageLevelFiltersSetting.get(),this.cancelBuildHiddenCache(),this.immediatelyFilterMessagesForTest){for(const e of this.consoleMessages)this.computeShouldMessageBeVisible(e);this.updateMessageList()}else this.buildHiddenCache(0,this.consoleMessages.slice())}setImmediatelyFilterMessagesForTest(){this.immediatelyFilterMessagesForTest=!0}searchableView(){return this.searchableViewInternal}clearHistory(){this.prompt.history().clear()}consoleHistoryAutocompleteChanged(){this.prompt.setAddCompletionsFromHistory(this.consoleHistoryAutocompleteSetting.get())}itemCount(){return this.visibleViewMessages.length}itemElement(e){return this.visibleViewMessages[e]}fastHeight(e){return this.visibleViewMessages[e].fastHeight()}minimumRowHeight(){return 16}registerWithMessageSink(){e.Console.Console.instance().messages().forEach(this.addSinkMessage,this),e.Console.Console.instance().addEventListener(e.Console.Events.MessageAdded,(({data:e})=>{this.addSinkMessage(e)}),this)}addSinkMessage(t){let s="verbose";switch(t.level){case e.Console.MessageLevel.Info:s="info";break;case e.Console.MessageLevel.Error:s="error";break;case e.Console.MessageLevel.Warning:s="warning"}const n=new o.ConsoleModel.ConsoleMessage(null,"other",s,t.text,{type:o.ConsoleModel.FrontendMessageType.System,timestamp:t.timestamp});this.addConsoleMessage(n)}consoleTimestampsSettingChanged(){this.updateMessageList(),this.consoleMessages.forEach((e=>e.updateTimestamp())),this.groupableMessageTitle.forEach((e=>e.updateTimestamp()))}executionContextChanged(){this.prompt.clearAutocomplete()}willHide(){this.hidePromptSuggestBox()}wasShown(){super.wasShown(),this.updateIssuesToolbarItem(),this.viewport.refresh(),this.registerCSSFiles([ne,O,g.Style.default])}focus(){this.viewport.hasVirtualSelection()?this.viewport.contentElement().focus():this.focusPrompt()}focusPrompt(){if(!this.prompt.hasFocus()){const e=this.viewport.stickToBottom(),t=this.viewport.element.scrollTop;this.prompt.focus(),this.viewport.setStickToBottom(e),this.viewport.element.scrollTop=t}}restoreScrollPositions(){this.viewport.stickToBottom()?this.immediatelyScrollToBottom():super.restoreScrollPositions()}onResize(){this.scheduleViewportRefresh(),this.hidePromptSuggestBox(),this.viewport.stickToBottom()&&this.immediatelyScrollToBottom();for(let e=0;e<this.visibleViewMessages.length;++e)this.visibleViewMessages[e].onResize()}hidePromptSuggestBox(){this.prompt.clearAutocomplete()}async invalidateViewport(){this.updateIssuesToolbarItem(),this.muteViewportUpdates?this.maybeDirtyWhileMuted=!0:this.needsFullUpdate?(this.updateMessageList(),delete this.needsFullUpdate):this.viewport.invalidate()}updateIssuesToolbarItem(){const e=S.IssuesManager.IssuesManager.instance(),t=f.IssueCounter.getIssueCountsEnumeration(e),s=0===e.numberOfIssues()?Pe(Fe.issueToolbarClickToGoToTheIssuesTab):Pe(Fe.issueToolbarClickToView,{issueEnumeration:t}),o=`${Pe(Fe.issueToolbarTooltipGeneral)} ${s}`;n.Tooltip.Tooltip.install(this.issueCounter,o),this.issueCounter.data={...this.issueCounter.data,leadingText:Pe(Fe.issuesWithColon,{n:e.numberOfIssues()}),accessibleName:o}}scheduleViewportRefresh(){this.muteViewportUpdates?this.maybeDirtyWhileMuted=!0:this.scheduledRefreshPromiseForTest=this.viewportThrottler.schedule(this.invalidateViewport.bind(this))}getScheduledRefreshPromiseForTest(){return this.scheduledRefreshPromiseForTest}immediatelyScrollToBottom(){this.viewport.setStickToBottom(!0),this.promptElement.scrollIntoView(!0)}updateFilterStatus(){this.hiddenByFilterCount!==this.lastShownHiddenByFilterCount&&(this.filterStatusText.setText(Pe(Fe.sHidden,{n:this.hiddenByFilterCount})),this.filterStatusText.setVisible(Boolean(this.hiddenByFilterCount)),this.lastShownHiddenByFilterCount=this.hiddenByFilterCount)}onConsoleMessageAdded(e){const t=e.data;this.addConsoleMessage(t)}addConsoleMessage(e){const t=this.createViewMessage(e);if(Ne.set(e,t),e.type===o.ConsoleModel.FrontendMessageType.Command||e.type===o.ConsoleModel.FrontendMessageType.Result){const e=this.consoleMessages[this.consoleMessages.length-1],s=e&&Ve.get(e)||0;Ve.set(t,s)}else Ve.set(t,t.consoleMessage().timestamp);let n;n=!this.consoleMessages.length||a(t,this.consoleMessages[this.consoleMessages.length-1])>0?this.consoleMessages.length:s.ArrayUtilities.upperBound(this.consoleMessages,t,a);const i=n<this.consoleMessages.length;if(this.consoleMessages.splice(n,0,t),e.type!==o.ConsoleModel.FrontendMessageType.Command&&e.type!==o.ConsoleModel.FrontendMessageType.Result){const o=s.ArrayUtilities.upperBound(this.consoleGroupStarts,t,a)-1;if(o>=0){!function e(t,s){const o=s.groupEnd();if(null!==o&&a(t,o)>0){const o=s.consoleGroup();if(null===o)return;return void e(t,o)}"endGroup"===t.consoleMessage().type?s.setGroupEnd(t):t.setConsoleGroup(s)}(t,this.consoleGroupStarts[o])}e.isGroupStartMessage()&&(n=s.ArrayUtilities.upperBound(this.consoleGroupStarts,t,a),this.consoleGroupStarts.splice(n,0,t))}this.filter.onMessageAdded(e),this.isSidebarOpen?this.sidebar.onMessageAdded(t):this.pendingSidebarMessages.push(t);let r=!1;const l=this.groupSimilarSetting.get();if(e.isGroupable()){const e=t.groupKey();r=l&&this.groupableMessages.has(e);let s=this.groupableMessages.get(e);s||(s=[],this.groupableMessages.set(e,s)),s.push(t)}function a(e,t){return(Ve.get(e)||0)-(Ve.get(t)||0)}this.computeShouldMessageBeVisible(t),r||i?this.needsFullUpdate=!0:(this.appendMessageToEnd(t,!l),this.updateFilterStatus(),this.searchableViewInternal.updateSearchMatchesCount(this.regexMatchRanges.length)),this.scheduleViewportRefresh(),this.consoleMessageAddedForTest(t)}onConsoleMessageUpdated(e){const t=e.data,s=Ne.get(t);s&&(s.updateMessageElement(),this.computeShouldMessageBeVisible(s),this.updateMessageList())}consoleMessageAddedForTest(e){}shouldMessageBeVisible(e){return!this.shouldBeHiddenCache.has(e)}computeShouldMessageBeVisible(e){!this.filter.shouldBeVisible(e)||this.isSidebarOpen&&!this.sidebar.shouldBeVisible(e)?this.shouldBeHiddenCache.add(e):this.shouldBeHiddenCache.delete(e)}appendMessageToEnd(e,t){if("cors"===e.consoleMessage().category&&!this.showCorsErrorsSetting.get())return;const s=this.visibleViewMessages[this.visibleViewMessages.length-1];if("endGroup"===e.consoleMessage().type){if(s){const e=s.consoleGroup();e&&!e.messagesHidden()&&s.incrementCloseGroupDecorationCount()}return}if(!this.shouldMessageBeVisible(e))return void this.hiddenByFilterCount++;if(!t&&this.tryToCollapseMessages(e,this.visibleViewMessages[this.visibleViewMessages.length-1]))return;const o=e.consoleGroup();if(!o||!o.messagesHidden()){const t=e.consoleMessage().originatingMessage(),n=Boolean(t&&s?.consoleMessage()===t);e.setAdjacentUserCommandResult(n),function e(t,s){if(null===t)return;if(s.includes(t))return;const o=t.consoleGroup();o&&e(o,s);s.push(t)}(o,this.visibleViewMessages),this.visibleViewMessages.push(e),this.searchMessage(this.visibleViewMessages.length-1)}this.messageAppendedForTests()}messageAppendedForTests(){}createViewMessage(e){switch(e.type){case o.ConsoleModel.FrontendMessageType.Command:return new xe(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);case o.ConsoleModel.FrontendMessageType.Result:return new Se(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);case"startGroupCollapsed":case"startGroup":return new we(e,this.linkifier,this.requestResolver,this.issueResolver,this.updateMessageList.bind(this),this.onMessageResizedBound);case"table":return new Ie(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound);default:return new ve(e,this.linkifier,this.requestResolver,this.issueResolver,this.onMessageResizedBound)}}async onMessageResized(e){const t=e.data;if(this.pendingBatchResize||!t.treeOutline)return;this.pendingBatchResize=!0,await Promise.resolve();const s=t.treeOutline.element;this.viewport.setStickToBottom(this.isScrolledToBottom()),s.offsetHeight<=this.messagesElement.offsetHeight&&s.scrollIntoViewIfNeeded(),this.pendingBatchResize=!1}consoleCleared(){const e=this.viewport.element.hasFocus();this.cancelBuildHiddenCache(),this.currentMatchRangeIndex=-1,this.consoleMessages=[],this.groupableMessages.clear(),this.groupableMessageTitle.clear(),this.sidebar.clear(),this.pendingSidebarMessages=[],this.updateMessageList(),this.hidePromptSuggestBox(),this.viewport.setStickToBottom(!0),this.linkifier.reset(),this.filter.clear(),this.requestResolver.clear(),this.consoleGroupStarts=[],e&&this.prompt.focus(),n.ARIAUtils.alert(Pe(Fe.consoleCleared))}handleContextMenuEvent(t){const s=new n.ContextMenu.ContextMenu(t),i=t.target;if(i.isSelfOrDescendant(this.promptElement))return void s.show();const r=i.enclosingNodeOrSelfWithClass("console-message-wrapper"),l=r&&pe(r),a=l?l.consoleMessage():null;if(a&&a.url){const t=Pe(Fe.hideMessagesFromS,{PH1:new e.ParsedURL.ParsedURL(a.url).displayName});s.headerSection().appendItem(t,this.filter.addMessageURLFilter.bind(this.filter,a.url))}if(s.defaultSection().appendAction("console.clear"),s.defaultSection().appendAction("console.clear.history"),s.saveSection().appendItem(Pe(Fe.saveAs),this.saveConsole.bind(this)),this.element.hasSelection()&&s.clipboardSection().appendItem(Pe(Fe.copyVisibleStyledSelection),this.viewport.copyWithStyles.bind(this.viewport)),a){const e=u.NetworkLog.NetworkLog.requestForConsoleMessage(a);e&&o.NetworkManager.NetworkManager.canReplayRequest(e)&&s.debugSection().appendItem(Pe(Fe.replayXhr),o.NetworkManager.NetworkManager.replayRequest.bind(null,e))}s.show()}async saveConsole(){const t=o.TargetManager.TargetManager.instance().scopeTarget().inspectedURL(),i=e.ParsedURL.ParsedURL.fromString(t),r=s.StringUtilities.sprintf("%s-%d.log",i?i.host:"console",Date.now()),l=new h.FileUtils.FileOutputStream,a=new n.ProgressIndicator.ProgressIndicator;a.setTitle(Pe(Fe.writingFile)),a.setTotalWork(this.itemCount());if(!await l.open(r))return;this.progressToolbarItem.element.appendChild(a.element);let c=0;for(;c<this.itemCount()&&!a.isCanceled();){const e=[];let t;for(t=0;t<350&&t+c<this.itemCount();++t){const s=this.itemElement(c+t);e.push(s.toExportString())}c+=t,await l.write(e.join("\n")+"\n"),a.setWorked(c)}l.close(),a.done()}tryToCollapseMessages(e,t){return!(this.timestampsSetting.get()||!t||e.consoleMessage().isGroupMessage()||e.consoleMessage().type===o.ConsoleModel.FrontendMessageType.Command||e.consoleMessage().type===o.ConsoleModel.FrontendMessageType.Result||!e.consoleMessage().isEqual(t.consoleMessage()))&&(t.incrementRepeatCount(),e.isLastInSimilarGroup()&&t.setInSimilarGroup(!0,!0),!0)}buildHiddenCache(e,t){const s=Date.now();let o;for(o=e;o<t.length&&(this.computeShouldMessageBeVisible(t[o]),!(o%10==0&&Date.now()-s>12));++o);o!==t.length?this.buildHiddenCacheTimeout=this.element.window().requestAnimationFrame(this.buildHiddenCache.bind(this,o+1,t)):this.updateMessageList()}cancelBuildHiddenCache(){this.shouldBeHiddenCache.clear(),this.buildHiddenCacheTimeout&&(this.element.window().cancelAnimationFrame(this.buildHiddenCacheTimeout),delete this.buildHiddenCacheTimeout)}updateMessageList(){this.regexMatchRanges=[],this.hiddenByFilterCount=0;for(const e of this.visibleViewMessages)e.resetCloseGroupDecorationCount(),e.resetIncrementRepeatCount();if(this.visibleViewMessages=[],this.groupSimilarSetting.get())this.addGroupableMessagesToEnd();else for(const e of this.consoleMessages)e.setInSimilarGroup(!1),e.consoleMessage().isGroupable()&&e.clearConsoleGroup(),this.appendMessageToEnd(e,!0);this.updateFilterStatus(),this.searchableViewInternal.updateSearchMatchesCount(this.regexMatchRanges.length),this.viewport.invalidate(),this.messagesCountElement.setAttribute("aria-label",Pe(Fe.filteredMessagesInConsole,{PH1:this.visibleViewMessages.length}))}addGroupableMessagesToEnd(){const e=new Set,t=new Set;for(const n of this.consoleMessages){const i=n.consoleMessage();if(e.has(i))continue;if(!i.isGroupable()){this.appendMessageToEnd(n),e.add(i);continue}const r=n.groupKey(),l=this.groupableMessages.get(r);if(!l||l.length<5){n.setInSimilarGroup(!1),this.appendMessageToEnd(n),e.add(i);continue}if(t.has(r))continue;if(!l.find((e=>this.shouldMessageBeVisible(e)))){s.SetUtilities.addAll(e,l),t.add(r);continue}let a=this.groupableMessageTitle.get(r);if(!a){const e=new o.ConsoleModel.ConsoleMessage(null,i.source,i.level,n.groupTitle(),{type:"startGroupCollapsed"});a=this.createViewMessage(e),this.groupableMessageTitle.set(r,a)}a.setRepeatCount(l.length),this.appendMessageToEnd(a);for(const t of l)t.setInSimilarGroup(!0,l[l.length-1]===t),t.setConsoleGroup(a),this.appendMessageToEnd(t,!0),e.add(t.consoleMessage());const c=new o.ConsoleModel.ConsoleMessage(null,i.source,i.level,i.messageText,{type:"endGroup"});this.appendMessageToEnd(this.createViewMessage(c))}}messagesClicked(e){const t=e.target;if(!this.messagesElement.hasSelection()){(t===this.messagesElement||this.prompt.belowEditorElement().isSelfOrAncestor(t))&&(this.prompt.moveCaretToEndOfPrompt(),this.focusPrompt())}}messagesKeyDown(e){const t=e;t.ctrlKey||t.altKey||t.metaKey||1!==t.key.length||n.UIUtils.isEditing()||this.messagesElement.hasSelection()||(this.prompt.moveCaretToEndOfPrompt(),this.focusPrompt())}messagesPasted(t){const s=o.TargetManager.TargetManager.instance().inspectedURL();"blockwebui"===r.Runtime.Runtime.queryParam("consolePaste")&&s.startsWith("chrome://")&&(t.preventDefault(),e.Console.Console.instance().error(Pe(Fe.consolePasteBlocked))),n.UIUtils.isEditing()||this.prompt.focus()}registerShortcuts(){this.shortcuts.set(n.KeyboardShortcut.KeyboardShortcut.makeKey("u",n.KeyboardShortcut.Modifiers.Ctrl),this.clearPromptBackwards.bind(this))}clearPromptBackwards(){this.prompt.clear()}promptKeyDown(e){const t=e;if("PageUp"===t.key)return void this.updateStickToBottomOnWheel();const s=n.KeyboardShortcut.KeyboardShortcut.makeKeyFromEvent(t),o=this.shortcuts.get(s);o&&(o(),t.preventDefault())}printResult(e,t,s){if(!e)return;const n=Boolean(s)?"error":"info";let i;i=s?o.ConsoleModel.ConsoleMessage.fromException(e.runtimeModel(),s,o.ConsoleModel.FrontendMessageType.Result,void 0,void 0):new o.ConsoleModel.ConsoleMessage(e.runtimeModel(),"javascript",n,"",{type:o.ConsoleModel.FrontendMessageType.Result,parameters:[e]}),i.setOriginatingMessage(t),e.runtimeModel().target().model(o.ConsoleModel.ConsoleModel)?.addMessage(i)}commandEvaluated(e){const{data:t}=e;this.prompt.history().pushHistoryItem(t.commandMessage.messageText),this.printResult(t.result,t.commandMessage,t.exceptionDetails)}elementsToRestoreScrollPositionsFor(){return[this.messagesElement]}onSearchCanceled(){this.cleanupAfterSearch();for(const e of this.visibleViewMessages)e.setSearchRegex(null);this.currentMatchRangeIndex=-1,this.regexMatchRanges=[],this.searchRegex=null,this.viewport.refresh()}performSearch(e,t,s){this.onSearchCanceled(),this.searchableViewInternal.updateSearchMatchesCount(0),this.searchRegex=e.toSearchRegex(!0).regex,this.regexMatchRanges=[],this.currentMatchRangeIndex=-1,t&&(this.searchShouldJumpBackwards=Boolean(s)),this.searchProgressIndicator=new n.ProgressIndicator.ProgressIndicator,this.searchProgressIndicator.setTitle(Pe(Fe.searching)),this.searchProgressIndicator.setTotalWork(this.visibleViewMessages.length),this.progressToolbarItem.element.appendChild(this.searchProgressIndicator.element),this.innerSearch(0)}cleanupAfterSearch(){delete this.searchShouldJumpBackwards,this.innerSearchTimeoutId&&(clearTimeout(this.innerSearchTimeoutId),delete this.innerSearchTimeoutId),this.searchProgressIndicator&&(this.searchProgressIndicator.done(),delete this.searchProgressIndicator)}searchFinishedForTests(){}innerSearch(e){if(delete this.innerSearchTimeoutId,this.searchProgressIndicator&&this.searchProgressIndicator.isCanceled())return void this.cleanupAfterSearch();const t=Date.now();for(;e<this.visibleViewMessages.length&&Date.now()-t<100;++e)this.searchMessage(e);if(this.searchableViewInternal.updateSearchMatchesCount(this.regexMatchRanges.length),void 0!==this.searchShouldJumpBackwards&&this.regexMatchRanges.length&&(this.jumpToMatch(this.searchShouldJumpBackwards?-1:0),delete this.searchShouldJumpBackwards),e===this.visibleViewMessages.length)return this.cleanupAfterSearch(),void window.setTimeout(this.searchFinishedForTests.bind(this),0);this.innerSearchTimeoutId=window.setTimeout(this.innerSearch.bind(this,e),100),this.searchProgressIndicator&&this.searchProgressIndicator.setWorked(e)}searchMessage(e){const t=this.visibleViewMessages[e];t.setSearchRegex(this.searchRegex);for(let s=0;s<t.searchCount();++s)this.regexMatchRanges.push({messageIndex:e,matchIndex:s})}jumpToNextSearchResult(){this.jumpToMatch(this.currentMatchRangeIndex+1)}jumpToPreviousSearchResult(){this.jumpToMatch(this.currentMatchRangeIndex-1)}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}jumpToMatch(e){if(!this.regexMatchRanges.length)return;let t;if(this.currentMatchRangeIndex>=0){t=this.regexMatchRanges[this.currentMatchRangeIndex];this.visibleViewMessages[t.messageIndex].searchHighlightNode(t.matchIndex).classList.remove(n.UIUtils.highlightedCurrentSearchResultClassName)}e=s.NumberUtilities.mod(e,this.regexMatchRanges.length),this.currentMatchRangeIndex=e,this.searchableViewInternal.updateCurrentMatchIndex(e),t=this.regexMatchRanges[e];const o=this.visibleViewMessages[t.messageIndex].searchHighlightNode(t.matchIndex);o.classList.add(n.UIUtils.highlightedCurrentSearchResultClassName),this.viewport.scrollItemIntoView(t.messageIndex),o.scrollIntoViewIfNeeded()}updateStickToBottomOnPointerDown(e){this.muteViewportUpdates=!e,this.viewport.setStickToBottom(!1),this.waitForScrollTimeout&&(clearTimeout(this.waitForScrollTimeout),delete this.waitForScrollTimeout)}updateStickToBottomOnPointerUp(){this.muteViewportUpdates&&(this.waitForScrollTimeout=window.setTimeout(function(){this.muteViewportUpdates=!1,this.isShowing()&&this.viewport.setStickToBottom(this.isScrolledToBottom());this.maybeDirtyWhileMuted&&(this.scheduleViewportRefresh(),delete this.maybeDirtyWhileMuted);delete this.waitForScrollTimeout,this.updateViewportStickinessForTest()}.bind(this),200))}updateViewportStickinessForTest(){}updateStickToBottomOnWheel(){this.updateStickToBottomOnPointerDown(),this.updateStickToBottomOnPointerUp()}promptTextChanged(){const e=this.viewport.stickToBottom(),t=this.isScrolledToBottom();this.viewport.setStickToBottom(t),t&&!e&&this.scheduleViewportRefresh(),this.promptTextChangedForTest()}promptTextChangedForTest(){}isScrolledToBottom(){return this.messagesElement.scrollHeight-this.messagesElement.scrollTop-this.messagesElement.clientHeight-this.prompt.belowEditorElement().offsetHeight<=2}}globalThis.Console=globalThis.Console||{},globalThis.Console.ConsoleView=He;class Ue{filterChanged;messageLevelFiltersSetting;hideNetworkMessagesSetting;filterByExecutionContextSetting;suggestionBuilder;textFilterUI;textFilterSetting;filterParser;currentFilter;levelLabels;levelMenuButton;constructor(t){this.filterChanged=t,this.messageLevelFiltersSetting=Ue.levelFilterSetting(),this.hideNetworkMessagesSetting=e.Settings.Settings.instance().moduleSetting("hideNetworkMessages"),this.filterByExecutionContextSetting=e.Settings.Settings.instance().moduleSetting("selectedContextFilterEnabled"),this.messageLevelFiltersSetting.addChangeListener(this.onFilterChanged.bind(this)),this.hideNetworkMessagesSetting.addChangeListener(this.onFilterChanged.bind(this)),this.filterByExecutionContextSetting.addChangeListener(this.onFilterChanged.bind(this)),n.Context.Context.instance().addFlavorChangeListener(o.RuntimeModel.ExecutionContext,this.onFilterChanged,this);const s=Object.values(k);this.suggestionBuilder=new n.FilterSuggestionBuilder.FilterSuggestionBuilder(s),this.textFilterUI=new n.Toolbar.ToolbarInput(Pe(Fe.filter),"",1,1,Pe(Fe.egEventdCdnUrlacom),this.suggestionBuilder.completions.bind(this.suggestionBuilder),!0),this.textFilterSetting=e.Settings.Settings.instance().createSetting("console.textFilter",""),this.textFilterSetting.get()&&this.textFilterUI.setValue(this.textFilterSetting.get()),this.textFilterUI.addEventListener(n.Toolbar.ToolbarInput.Event.TextChanged,(()=>{this.textFilterSetting.set(this.textFilterUI.value()),this.onFilterChanged()})),this.filterParser=new i.TextUtils.FilterParser(s),this.currentFilter=new F("",[],null,this.messageLevelFiltersSetting.get()),this.updateCurrentFilter(),this.levelLabels=new Map([["verbose",Pe(Fe.verbose)],["info",Pe(Fe.info)],["warning",Pe(Fe.warnings)],["error",Pe(Fe.errors)]]),this.levelMenuButton=new n.Toolbar.ToolbarButton(Pe(Fe.logLevels)),this.levelMenuButton.turnIntoSelect(),this.levelMenuButton.addEventListener(n.Toolbar.ToolbarButton.Events.Click,this.showLevelContextMenu.bind(this)),n.ARIAUtils.markAsMenuButton(this.levelMenuButton.element),this.updateLevelMenuButtonText(),this.messageLevelFiltersSetting.addChangeListener(this.updateLevelMenuButtonText.bind(this))}onMessageAdded(e){e.type===o.ConsoleModel.FrontendMessageType.Command||e.type===o.ConsoleModel.FrontendMessageType.Result||e.isGroupMessage()||(e.context&&this.suggestionBuilder.addItem(k.Context,e.context),e.source&&this.suggestionBuilder.addItem(k.Source,e.source),e.url&&this.suggestionBuilder.addItem(k.Url,e.url))}setLevelMenuOverridden(e){this.levelMenuButton.setEnabled(!e),e?this.levelMenuButton.setTitle(Pe(Fe.overriddenByFilterSidebar)):this.updateLevelMenuButtonText()}static levelFilterSetting(){return e.Settings.Settings.instance().createSetting("messageLevelFilters",F.defaultLevelsFilterValue())}updateCurrentFilter(){const e=this.filterParser.parse(this.textFilterUI.value());this.hideNetworkMessagesSetting.get()&&e.push({key:k.Source,text:"network",negative:!0,regex:void 0}),this.currentFilter.executionContext=this.filterByExecutionContextSetting.get()?n.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext):null,this.currentFilter.parsedFilters=e,this.currentFilter.levelsMask=this.messageLevelFiltersSetting.get()}onFilterChanged(){this.updateCurrentFilter(),this.filterChanged()}updateLevelMenuButtonText(){let e=!0,t=!0;const s=F.allLevelsFilterValue(),o=F.defaultLevelsFilterValue();let n=null;const i=this.messageLevelFiltersSetting.get(),r={Verbose:"verbose",Info:"info",Warning:"warning",Error:"error"};for(const l of Object.values(r))e=e&&i[l]===s[l],t=t&&i[l]===o[l],i[l]&&(n=n?Pe(Fe.customLevels):Pe(Fe.sOnly,{PH1:String(this.levelLabels.get(l))}));n=e?Pe(Fe.allLevels):t?Pe(Fe.defaultLevels):n||Pe(Fe.hideAll),this.levelMenuButton.element.classList.toggle("warning",!e&&!t),this.levelMenuButton.setText(n),this.levelMenuButton.setTitle(Pe(Fe.logLevelS,{PH1:n}))}showLevelContextMenu(e){const t=e.data,s=this.messageLevelFiltersSetting,o=s.get(),i=new n.ContextMenu.ContextMenu(t,{useSoftMenu:!0,x:this.levelMenuButton.element.getBoundingClientRect().left,y:this.levelMenuButton.element.getBoundingClientRect().top+this.levelMenuButton.element.offsetHeight});i.headerSection().appendItem(Pe(Fe.default),(()=>s.set(F.defaultLevelsFilterValue())));for(const[e,t]of this.levelLabels.entries())i.defaultSection().appendCheckboxItem(t,r.bind(null,e),o[e]);function r(e){o[e]=!o[e],s.set(o)}i.show()}addMessageURLFilter(e){if(!e)return;const t=this.textFilterUI.value()?` ${this.textFilterUI.value()}`:"";this.textFilterUI.setValue(`-url:${e}${t}`),this.textFilterSetting.set(this.textFilterUI.value()),this.onFilterChanged()}shouldBeVisible(e){return this.currentFilter.shouldBeVisible(e)}clear(){this.suggestionBuilder.clear()}reset(){this.messageLevelFiltersSetting.set(F.defaultLevelsFilterValue()),this.filterByExecutionContextSetting.set(!1),this.hideNetworkMessagesSetting.set(!1),this.textFilterUI.setValue(""),this.onFilterChanged()}}class Oe{handleAction(t,s){switch(s){case"console.show":return m.InspectorFrontendHost.InspectorFrontendHostInstance.bringToFront(),e.Console.Console.instance().show(),He.instance().focusPrompt(),!0;case"console.clear":return He.clearConsole(),!0;case"console.clear.history":return He.instance().clearHistory(),!0;case"console.create-pin":return He.instance().pinPane.addPin("",!0),!0}return!1}static instance(e={forceNew:null}){const{forceNew:t}=e;return Be&&!t||(Be=new Oe),Be}}const Ve=new WeakMap,Ne=new WeakMap;var je=Object.freeze({__proto__:null,ConsoleView:He,ConsoleViewFilter:Ue,ActionDelegate:Oe});let Ge;class De extends n.Panel.Panel{view;constructor(){super("console"),this.view=He.instance()}static instance(e={forceNew:null}){const{forceNew:t}=e;return Ge&&!t||(Ge=new De),Ge}static updateContextFlavor(){const e=De.instance().view;n.Context.Context.instance().setFlavor(He,e.isShowing()?e:null)}wasShown(){super.wasShown();_e&&_e.isShowing()&&n.InspectorView.InspectorView.instance().setDrawerMinimized(!0),this.view.show(this.element),De.updateContextFlavor()}willHide(){super.willHide(),n.InspectorView.InspectorView.instance().setDrawerMinimized(!1),_e&&_e.showViewInWrapper(),De.updateContextFlavor()}searchableView(){return He.instance().searchableView()}}let We,_e=null;class ze extends n.Widget.VBox{view;constructor(){super(),this.view=He.instance()}static instance(){return _e||(_e=new ze),_e}wasShown(){De.instance().isShowing()?n.InspectorView.InspectorView.instance().setDrawerMinimized(!0):this.showViewInWrapper(),De.updateContextFlavor()}willHide(){n.InspectorView.InspectorView.instance().setDrawerMinimized(!1),De.updateContextFlavor()}showViewInWrapper(){this.view.show(this.element)}}class qe{static instance(e={forceNew:null}){const{forceNew:t}=e;return We&&!t||(We=new qe),We}async reveal(e){const t=He.instance();t.isShowing()?t.focus():await n.ViewManager.ViewManager.instance().showView("console-view")}}var $e=Object.freeze({__proto__:null,ConsolePanel:De,WrapperView:ze,ConsoleRevealer:qe});const Ke=new CSSStyleSheet;Ke.replaceSync("#console-prompt .CodeMirror{padding:3px 0 1px}#console-prompt .CodeMirror-line{padding-top:0}#console-prompt .CodeMirror-lines{padding-top:0}#console-prompt .console-prompt-icon{position:absolute;left:-13px;top:2px;user-select:none}.console-eager-preview{padding-bottom:2px;opacity:60%;position:relative;height:15px}.console-eager-inner-preview{text-overflow:ellipsis;overflow:hidden;margin-left:4px;height:100%;white-space:nowrap}.preview-result-icon{position:absolute;left:-13px;top:-1px}.console-eager-inner-preview:empty,\n.console-eager-inner-preview:empty + .preview-result-icon{opacity:0%}.console-prompt-icon.console-prompt-incomplete{opacity:65%}\n/*# sourceURL=consolePrompt.css */\n");const{Direction:Je}=a.TextEditorHistory,Xe={consolePrompt:"Console prompt"},Ze=t.i18n.registerUIStrings("panels/console/ConsolePrompt.ts",Xe),Qe=t.i18n.getLocalizedString.bind(void 0,Ze);class Ye extends(e.ObjectWrapper.eventMixin(n.Widget.Widget)){addCompletionsFromHistory;historyInternal;initialText;editor;eagerPreviewElement;textChangeThrottler;formatter;requestPreviewBound;requestPreviewCurrent=0;innerPreviewElement;promptIcon;iconThrottler;eagerEvalSetting;previewRequestForTest;highlightingNode;#o;#n;constructor(){super(),this.addCompletionsFromHistory=!0,this.historyInternal=new a.AutocompleteHistory.AutocompleteHistory(e.Settings.Settings.instance().createLocalSetting("consoleHistory",[])),this.initialText="",this.eagerPreviewElement=document.createElement("div"),this.eagerPreviewElement.classList.add("console-eager-preview"),this.textChangeThrottler=new e.Throttler.Throttler(150),this.formatter=new c.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,this.requestPreviewBound=this.requestPreview.bind(this),this.innerPreviewElement=this.eagerPreviewElement.createChild("div","console-eager-inner-preview");const t=new v.Icon.Icon;t.data={iconName:"chevron-left-dot",color:"var(--icon-default)",width:"16px",height:"16px"},t.classList.add("preview-result-icon"),this.eagerPreviewElement.appendChild(t);const s=this.element.createChild("div","console-prompt-editor-container");this.element.appendChild(this.eagerPreviewElement),this.promptIcon=new v.Icon.Icon,this.promptIcon.data={iconName:"chevron-right",color:"var(--icon-action)",width:"16px",height:"16px"},this.promptIcon.classList.add("console-prompt-icon"),this.element.appendChild(this.promptIcon),this.iconThrottler=new e.Throttler.Throttler(0),this.eagerEvalSetting=e.Settings.Settings.instance().moduleSetting("consoleEagerEval"),this.eagerEvalSetting.addChangeListener(this.eagerSettingChanged.bind(this)),this.eagerPreviewElement.classList.toggle("hidden",!this.eagerEvalSetting.get()),this.element.tabIndex=0,this.previewRequestForTest=null,this.highlightingNode=!1;const o=a.JavaScript.argumentHints();this.#o=o[0];const n=a.Config.DynamicSetting.bool("consoleAutocompleteOnEnter",[],a.Config.conservativeCompletion),i=[l.keymap.of(this.editorKeymap()),l.EditorView.updateListener.of((e=>this.editorUpdate(e))),o,n.instance(),a.Config.showCompletionHint,a.Config.baseConfiguration(this.initialText),a.Config.autocompletion.instance(),l.javascript.javascriptLanguage.data.of({autocomplete:e=>this.addCompletionsFromHistory?this.#n.historyCompletions(e):null}),l.EditorView.contentAttributes.of({"aria-label":Qe(Xe.consolePrompt)}),l.EditorView.lineWrapping,l.autocompletion({aboveCursor:!0})];"true"!==r.Runtime.Runtime.queryParam("noJavaScriptCompletion")?i.push(l.javascript.javascript(),a.JavaScript.completion()):i.push(l.javascript.javascriptLanguage);const d=this.initialText,h=l.EditorState.create({doc:d,extensions:i});this.editor=new a.TextEditor.TextEditor(h),this.editor.addEventListener("keydown",(e=>{e.defaultPrevented&&e.stopPropagation()})),s.appendChild(this.editor),this.#n=new a.TextEditorHistory.TextEditorHistory(this.editor,this.historyInternal),this.hasFocus()&&this.focus(),this.element.removeAttribute("tabindex"),this.editorSetForTest(),m.userMetrics.panelLoaded("console","DevTools.Launch.Console")}eagerSettingChanged(){const e=this.eagerEvalSetting.get();this.eagerPreviewElement.classList.toggle("hidden",!e),e&&this.requestPreview()}belowEditorElement(){return this.eagerPreviewElement}onTextChanged(){if(this.eagerEvalSetting.get()){const e=!a.Config.contentIncludingHint(this.editor.editor);this.previewRequestForTest=this.textChangeThrottler.schedule(this.requestPreviewBound,e)}this.updatePromptIcon(),this.dispatchEventToListeners("TextChanged")}async requestPreview(){const e=++this.requestPreviewCurrent,t=a.Config.contentIncludingHint(this.editor.editor).trim(),s=n.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext),{preview:i,result:r}=await c.JavaScriptREPL.JavaScriptREPL.evaluateAndBuildPreview(t,!0,!0,500);this.requestPreviewCurrent===e&&(this.innerPreviewElement.removeChildren(),i.deepTextContent()!==a.Config.contentIncludingHint(this.editor.editor).trim()&&this.innerPreviewElement.appendChild(i),r&&"object"in r&&r.object&&"node"===r.object.subtype?(this.highlightingNode=!0,o.OverlayModel.OverlayModel.highlightObjectAsDOMNode(r.object)):this.highlightingNode&&(this.highlightingNode=!1,o.OverlayModel.OverlayModel.hideDOMNodeHighlight()),r&&s&&s.runtimeModel.releaseEvaluationResult(r))}wasShown(){super.wasShown(),this.registerCSSFiles([Ke])}willHide(){this.highlightingNode&&(this.highlightingNode=!1,o.OverlayModel.OverlayModel.hideDOMNodeHighlight())}history(){return this.historyInternal}clearAutocomplete(){l.closeCompletion(this.editor.editor)}isCaretAtEndOfPrompt(){return this.editor.state.selection.main.head===this.editor.state.doc.length}moveCaretToEndOfPrompt(){this.editor.dispatch({selection:l.EditorSelection.cursor(this.editor.state.doc.length)})}clear(){this.editor.dispatch({changes:{from:0,to:this.editor.state.doc.length}})}text(){return this.editor.state.doc.toString()}setAddCompletionsFromHistory(e){this.addCompletionsFromHistory=e}editorKeymap(){return[{key:"ArrowUp",run:()=>this.#n.moveHistory(-1)},{key:"ArrowDown",run:()=>this.#n.moveHistory(1)},{mac:"Ctrl-p",run:()=>this.#n.moveHistory(-1,!0)},{mac:"Ctrl-n",run:()=>this.#n.moveHistory(1,!0)},{key:"Escape",run:()=>a.JavaScript.closeArgumentsHintsTooltip(this.editor.editor,this.#o)},{key:"Ctrl-Enter",run:()=>(this.handleEnter(!0),!0)},{key:"Enter",run:()=>(this.handleEnter(),!0),shift:l.insertNewlineAndIndent}]}async enterWillEvaluate(e){const{doc:t,selection:s}=this.editor.state;return!!t.length&&(!!(e||s.main.head<t.length)||await a.JavaScript.isExpressionComplete(t.toString()))}async handleEnter(e){await this.enterWillEvaluate(e)?(this.appendCommand(this.text(),!0),a.JavaScript.closeArgumentsHintsTooltip(this.editor.editor,this.#o),this.editor.dispatch({changes:{from:0,to:this.editor.state.doc.length},scrollIntoView:!0})):this.editor.state.doc.length?l.insertNewlineAndIndent(this.editor.editor):this.editor.dispatch({scrollIntoView:!0})}updatePromptIcon(){this.iconThrottler.schedule((async()=>{this.promptIcon.classList.toggle("console-prompt-incomplete",!await this.enterWillEvaluate())}))}appendCommand(e,t){const s=n.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext);if(s){const n=s,i=n.target().model(o.ConsoleModel.ConsoleModel);if(i){const s=i.addCommandMessage(n,e),o=c.JavaScriptREPL.JavaScriptREPL.wrapObjectLiteral(e);this.evaluateCommandInConsole(n,s,o,t),De.instance().isShowing()&&m.userMetrics.actionTaken(m.UserMetrics.Action.CommandEvaluatedInConsolePanel)}}}async evaluateCommandInConsole(e,t,s,n){if(r.Runtime.experiments.isEnabled("evaluateExpressionsWithSourceMaps")){const t=e.debuggerModel.selectedCallFrame();if(t){const e=await x.NamesResolver.allVariablesInCallFrame(t);s=await this.substituteNames(s,e)}}await(e.target().model(o.ConsoleModel.ConsoleModel)?.evaluateCommandInConsole(e,t,s,n))}async substituteNames(e,t){try{return await w.FormatterWorkerPool.formatterWorkerPool().javaScriptSubstitute(e,t)}catch{return e}}editorUpdate(e){e.docChanged||l.selectedCompletion(e.state)!==l.selectedCompletion(e.startState)?this.onTextChanged():e.selectionSet&&this.updatePromptIcon()}focus(){this.editor.focus()}editorSetForTest(){}}var et=Object.freeze({__proto__:null,ConsolePrompt:Ye});export{L as ConsoleContextSelector,R as ConsoleFilter,U as ConsoleFormat,$e as ConsolePanel,z as ConsolePinPane,et as ConsolePrompt,te as ConsoleSidebar,je as ConsoleView,Le as ConsoleViewMessage,oe as ConsoleViewport,ce as ErrorStackParser};
